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.

67 lines
2.1 KiB

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