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

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