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.0 KiB

7 years ago
6 years ago
5 years ago
5 years ago
  1. package postgres
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/filer/abstract_sql"
  7. "github.com/chrislusf/seaweedfs/weed/util"
  8. _ "github.com/lib/pq"
  9. )
  10. const (
  11. CONNECTION_URL_PATTERN = "host=%s port=%d sslmode=%s connect_timeout=30"
  12. )
  13. func init() {
  14. filer.Stores = append(filer.Stores, &PostgresStore{})
  15. }
  16. type PostgresStore struct {
  17. abstract_sql.AbstractSqlStore
  18. }
  19. func (store *PostgresStore) GetName() string {
  20. return "postgres"
  21. }
  22. func (store *PostgresStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  23. return store.initialize(
  24. configuration.GetString(prefix+"username"),
  25. configuration.GetString(prefix+"password"),
  26. configuration.GetString(prefix+"hostname"),
  27. configuration.GetInt(prefix+"port"),
  28. configuration.GetString(prefix+"database"),
  29. configuration.GetString(prefix+"schema"),
  30. configuration.GetString(prefix+"sslmode"),
  31. configuration.GetInt(prefix+"connection_max_idle"),
  32. configuration.GetInt(prefix+"connection_max_open"),
  33. )
  34. }
  35. func (store *PostgresStore) initialize(user, password, hostname string, port int, database, schema, sslmode string, maxIdle, maxOpen int) (err error) {
  36. store.SupportBucketTable = false
  37. store.SqlGenerator = &SqlGenPostgres{
  38. CreateTableSqlTemplate: "",
  39. DropTableSqlTemplate: "drop table %s",
  40. }
  41. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, hostname, port, sslmode)
  42. if user != "" {
  43. sqlUrl += " user=" + user
  44. }
  45. if password != "" {
  46. sqlUrl += " password=" + password
  47. }
  48. if database != "" {
  49. sqlUrl += " dbname=" + database
  50. }
  51. if schema != "" {
  52. sqlUrl += " search_path=" + schema
  53. }
  54. var dbErr error
  55. store.DB, dbErr = sql.Open("postgres", sqlUrl)
  56. if dbErr != nil {
  57. store.DB.Close()
  58. store.DB = nil
  59. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  60. }
  61. store.DB.SetMaxIdleConns(maxIdle)
  62. store.DB.SetMaxOpenConns(maxOpen)
  63. if err = store.DB.Ping(); err != nil {
  64. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  65. }
  66. return nil
  67. }