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.

68 lines
2.2 KiB

7 years ago
6 years ago
7 years ago
  1. package postgres
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer2"
  6. "github.com/chrislusf/seaweedfs/weed/filer2/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 user=%s password=%s dbname=%s sslmode=%s connect_timeout=30"
  12. )
  13. func init() {
  14. filer2.Stores = append(filer2.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) (err error) {
  23. return store.initialize(
  24. configuration.GetString("username"),
  25. configuration.GetString("password"),
  26. configuration.GetString("hostname"),
  27. configuration.GetInt("port"),
  28. configuration.GetString("database"),
  29. configuration.GetString("sslmode"),
  30. configuration.GetInt("connection_max_idle"),
  31. configuration.GetInt("connection_max_open"),
  32. )
  33. }
  34. func (store *PostgresStore) initialize(user, password, hostname string, port int, database, sslmode string, maxIdle, maxOpen int) (err error) {
  35. store.SqlInsert = "INSERT INTO filemeta (dirhash,name,directory,meta) VALUES($1,$2,$3,$4)"
  36. store.SqlUpdate = "UPDATE filemeta SET meta=$1 WHERE dirhash=$2 AND name=$3 AND directory=$4"
  37. store.SqlFind = "SELECT meta FROM filemeta WHERE dirhash=$1 AND name=$2 AND directory=$3"
  38. store.SqlDelete = "DELETE FROM filemeta WHERE dirhash=$1 AND name=$2 AND directory=$3"
  39. store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=$1 AND name>$2 AND directory=$3 ORDER BY NAME ASC LIMIT $4"
  40. store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=$1 AND name>=$2 AND directory=$3 ORDER BY NAME ASC LIMIT $4"
  41. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, hostname, port, user, password, database, sslmode)
  42. var dbErr error
  43. store.DB, dbErr = sql.Open("postgres", sqlUrl)
  44. if dbErr != nil {
  45. store.DB.Close()
  46. store.DB = nil
  47. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  48. }
  49. store.DB.SetMaxIdleConns(maxIdle)
  50. store.DB.SetMaxOpenConns(maxOpen)
  51. if err = store.DB.Ping(); err != nil {
  52. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  53. }
  54. return nil
  55. }