postgres_store.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package postgres
  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/lib/pq"
  10. )
  11. const (
  12. CONNECTION_URL_PATTERN = "host=%s port=%d sslmode=%s connect_timeout=30"
  13. )
  14. func init() {
  15. filer.Stores = append(filer.Stores, &PostgresStore{})
  16. }
  17. type PostgresStore struct {
  18. abstract_sql.AbstractSqlStore
  19. }
  20. func (store *PostgresStore) GetName() string {
  21. return "postgres"
  22. }
  23. func (store *PostgresStore) 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.GetString(prefix+"schema"),
  31. configuration.GetString(prefix+"sslmode"),
  32. configuration.GetInt(prefix+"connection_max_idle"),
  33. configuration.GetInt(prefix+"connection_max_open"),
  34. configuration.GetInt(prefix+"connection_max_lifetime_seconds"),
  35. )
  36. }
  37. func (store *PostgresStore) initialize(user, password, hostname string, port int, database, schema, sslmode string, maxIdle, maxOpen, maxLifetimeSeconds int) (err error) {
  38. store.SupportBucketTable = false
  39. store.SqlGenerator = &SqlGenPostgres{
  40. CreateTableSqlTemplate: "",
  41. DropTableSqlTemplate: `drop table "%s"`,
  42. }
  43. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, hostname, port, sslmode)
  44. if user != "" {
  45. sqlUrl += " user=" + user
  46. }
  47. adaptedSqlUrl := sqlUrl
  48. if password != "" {
  49. sqlUrl += " password=" + password
  50. adaptedSqlUrl += " password=ADAPTED"
  51. }
  52. if database != "" {
  53. sqlUrl += " dbname=" + database
  54. adaptedSqlUrl += " dbname=" + database
  55. }
  56. if schema != "" {
  57. sqlUrl += " search_path=" + schema
  58. adaptedSqlUrl += " search_path=" + schema
  59. }
  60. var dbErr error
  61. store.DB, dbErr = sql.Open("postgres", sqlUrl)
  62. if dbErr != nil {
  63. store.DB.Close()
  64. store.DB = nil
  65. return fmt.Errorf("can not connect to %s error:%v", adaptedSqlUrl, err)
  66. }
  67. store.DB.SetMaxIdleConns(maxIdle)
  68. store.DB.SetMaxOpenConns(maxOpen)
  69. store.DB.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
  70. if err = store.DB.Ping(); err != nil {
  71. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  72. }
  73. return nil
  74. }