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.3 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.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. }