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.

84 lines
2.4 KiB

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