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.

77 lines
2.1 KiB

7 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
  1. package mysql
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/filer/abstract_sql"
  8. "github.com/chrislusf/seaweedfs/weed/util"
  9. _ "github.com/go-sql-driver/mysql"
  10. )
  11. const (
  12. CONNECTION_URL_PATTERN = "%s:%s@tcp(%s:%d)/%s?charset=utf8"
  13. )
  14. func init() {
  15. filer.Stores = append(filer.Stores, &MysqlStore{})
  16. }
  17. type MysqlStore struct {
  18. abstract_sql.AbstractSqlStore
  19. }
  20. func (store *MysqlStore) GetName() string {
  21. return "mysql"
  22. }
  23. func (store *MysqlStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  24. return store.initialize(
  25. configuration.GetString(prefix+"username"),
  26. configuration.GetString(prefix+"password"),
  27. configuration.GetString(prefix+"hostname"),
  28. configuration.GetInt(prefix+"port"),
  29. configuration.GetString(prefix+"database"),
  30. configuration.GetInt(prefix+"connection_max_idle"),
  31. configuration.GetInt(prefix+"connection_max_open"),
  32. configuration.GetInt(prefix+"connection_max_lifetime_seconds"),
  33. configuration.GetBool(prefix+"interpolateParams"),
  34. )
  35. }
  36. func (store *MysqlStore) initialize(user, password, hostname string, port int, database string, maxIdle, maxOpen,
  37. maxLifetimeSeconds int, interpolateParams bool) (err error) {
  38. store.SupportBucketTable = false
  39. store.SqlGenerator = &SqlGenMysql{
  40. CreateTableSqlTemplate: "",
  41. DropTableSqlTemplate: "drop table `%s`",
  42. }
  43. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  44. adaptedSqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, "<ADAPTED>", hostname, port, database)
  45. if interpolateParams {
  46. sqlUrl += "&interpolateParams=true"
  47. adaptedSqlUrl += "&interpolateParams=true"
  48. }
  49. var dbErr error
  50. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  51. if dbErr != nil {
  52. store.DB.Close()
  53. store.DB = nil
  54. return fmt.Errorf("can not connect to %s error:%v", adaptedSqlUrl, err)
  55. }
  56. store.DB.SetMaxIdleConns(maxIdle)
  57. store.DB.SetMaxOpenConns(maxOpen)
  58. store.DB.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
  59. if err = store.DB.Ping(); err != nil {
  60. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  61. }
  62. return nil
  63. }