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.

66 lines
2.0 KiB

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