You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.2 KiB

7 years ago
6 years ago
7 years ago
  1. package mysql
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer2"
  6. "github.com/chrislusf/seaweedfs/weed/filer2/abstract_sql"
  7. "github.com/chrislusf/seaweedfs/weed/util"
  8. _ "github.com/go-sql-driver/mysql"
  9. )
  10. const (
  11. CONNECTION_URL_PATTERN = "%s:%s@tcp(%s:%d)/%s?charset=utf8"
  12. )
  13. func init() {
  14. filer2.Stores = append(filer2.Stores, &MysqlStore{})
  15. }
  16. type MysqlStore struct {
  17. abstract_sql.AbstractSqlStore
  18. }
  19. func (store *MysqlStore) GetName() string {
  20. return "mysql"
  21. }
  22. func (store *MysqlStore) Initialize(configuration util.Configuration) (err error) {
  23. return store.initialize(
  24. configuration.GetString("username"),
  25. configuration.GetString("password"),
  26. configuration.GetString("hostname"),
  27. configuration.GetInt("port"),
  28. configuration.GetString("database"),
  29. configuration.GetInt("connection_max_idle"),
  30. configuration.GetInt("connection_max_open"),
  31. configuration.GetBool("interpolateParams"),
  32. )
  33. }
  34. func (store *MysqlStore) initialize(user, password, hostname string, port int, database string, maxIdle, maxOpen int,
  35. interpolateParams bool) (err error) {
  36. store.SqlInsert = "INSERT INTO filemeta (dirhash,name,directory,meta) VALUES(?,?,?,?)"
  37. store.SqlUpdate = "UPDATE filemeta SET meta=? WHERE dirhash=? AND name=? AND directory=?"
  38. store.SqlFind = "SELECT meta FROM filemeta WHERE dirhash=? AND name=? AND directory=?"
  39. store.SqlDelete = "DELETE FROM filemeta WHERE dirhash=? AND name=? AND directory=?"
  40. store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>? AND directory=? ORDER BY NAME ASC LIMIT ?"
  41. store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>=? AND directory=? ORDER BY NAME ASC LIMIT ?"
  42. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  43. if interpolateParams {
  44. sqlUrl += "&interpolateParams=true"
  45. }
  46. var dbErr error
  47. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  48. if dbErr != nil {
  49. store.DB.Close()
  50. store.DB = nil
  51. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  52. }
  53. store.DB.SetMaxIdleConns(maxIdle)
  54. store.DB.SetMaxOpenConns(maxOpen)
  55. if err = store.DB.Ping(); err != nil {
  56. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  57. }
  58. return nil
  59. }