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.

80 lines
2.2 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. "time"
  6. "github.com/chrislusf/seaweedfs/weed/filer"
  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+"insertQuery"),
  26. configuration.GetString(prefix+"username"),
  27. configuration.GetString(prefix+"password"),
  28. configuration.GetString(prefix+"hostname"),
  29. configuration.GetInt(prefix+"port"),
  30. configuration.GetString(prefix+"database"),
  31. configuration.GetInt(prefix+"connection_max_idle"),
  32. configuration.GetInt(prefix+"connection_max_open"),
  33. configuration.GetInt(prefix+"connection_max_lifetime_seconds"),
  34. configuration.GetBool(prefix+"interpolateParams"),
  35. )
  36. }
  37. func (store *MysqlStore) initialize(insertQuery, user, password, hostname string, port int, database string, maxIdle, maxOpen,
  38. maxLifetimeSeconds int, interpolateParams bool) (err error) {
  39. store.SupportBucketTable = false
  40. store.SqlGenerator = &SqlGenMysql{
  41. CreateTableSqlTemplate: "",
  42. DropTableSqlTemplate: "drop table `%s`",
  43. InsertQueryTemplate: insertQuery,
  44. }
  45. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  46. adaptedSqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, "<ADAPTED>", hostname, port, database)
  47. if interpolateParams {
  48. sqlUrl += "&interpolateParams=true"
  49. adaptedSqlUrl += "&interpolateParams=true"
  50. }
  51. var dbErr error
  52. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  53. if dbErr != nil {
  54. store.DB.Close()
  55. store.DB = nil
  56. return fmt.Errorf("can not connect to %s error:%v", adaptedSqlUrl, err)
  57. }
  58. store.DB.SetMaxIdleConns(maxIdle)
  59. store.DB.SetMaxOpenConns(maxOpen)
  60. store.DB.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
  61. if err = store.DB.Ping(); err != nil {
  62. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  63. }
  64. return nil
  65. }