mysql_store.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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, prefix string) (err error) {
  23. return store.initialize(
  24. configuration.GetString(prefix+"username"),
  25. configuration.GetString(prefix+"password"),
  26. configuration.GetString(prefix+"hostname"),
  27. configuration.GetInt(prefix+"port"),
  28. configuration.GetString(prefix+"database"),
  29. configuration.GetInt(prefix+"connection_max_idle"),
  30. configuration.GetInt(prefix+"connection_max_open"),
  31. configuration.GetBool(prefix+"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.SqlDeleteFolderChildren = "DELETE FROM filemeta WHERE dirhash=? AND directory=?"
  41. store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>? AND directory=? ORDER BY NAME ASC LIMIT ?"
  42. store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>=? AND directory=? ORDER BY NAME ASC LIMIT ?"
  43. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  44. if interpolateParams {
  45. sqlUrl += "&interpolateParams=true"
  46. }
  47. var dbErr error
  48. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  49. if dbErr != nil {
  50. store.DB.Close()
  51. store.DB = nil
  52. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  53. }
  54. store.DB.SetMaxIdleConns(maxIdle)
  55. store.DB.SetMaxOpenConns(maxOpen)
  56. if err = store.DB.Ping(); err != nil {
  57. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  58. }
  59. return nil
  60. }