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.

87 lines
2.3 KiB

7 years ago
6 years ago
5 years ago
5 years ago
  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. }