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.

74 lines
2.4 KiB

7 years ago
6 years ago
  1. package mysql
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/filer/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. filer.Stores = append(filer.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. //
  37. store.SqlInsert = "INSERT INTO filemeta (dirhash,name,directory,meta) VALUES(?,?,?,?)"
  38. store.SqlUpdate = "UPDATE filemeta SET meta=? WHERE dirhash=? AND name=? AND directory=?"
  39. store.SqlFind = "SELECT meta FROM filemeta WHERE dirhash=? AND name=? AND directory=?"
  40. store.SqlDelete = "DELETE FROM filemeta WHERE dirhash=? AND name=? AND directory=?"
  41. store.SqlDeleteFolderChildren = "DELETE FROM filemeta WHERE dirhash=? AND directory=?"
  42. store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>? AND directory=? AND name like ? ORDER BY NAME ASC LIMIT ?"
  43. store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>=? AND directory=? AND name like ? ORDER BY NAME ASC LIMIT ?"
  44. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  45. if interpolateParams {
  46. sqlUrl += "&interpolateParams=true"
  47. }
  48. var dbErr error
  49. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  50. if dbErr != nil {
  51. store.DB.Close()
  52. store.DB = nil
  53. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  54. }
  55. store.DB.SetMaxIdleConns(maxIdle)
  56. store.DB.SetMaxOpenConns(maxOpen)
  57. if err = store.DB.Ping(); err != nil {
  58. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  59. }
  60. return nil
  61. }