package dao import ( "database/sql" "fmt" "github.com/kratisto/mam-contract/configuration" _ "github.com/lib/pq" // Required to use the driver with database/sql ) // Database is the interface for DB access type Database interface { Ping() error } // DatabasePostgreSQL is the implementation of the Database interface for PostgreSQL type DatabasePostgreSQL struct { session *sql.DB schema string } // NewDatabasePostgreSQL returns an instance of the database func NewDatabasePostgreSQL(config *configuration.Config) Database { var ( dbSession *sql.DB err error ) connectionURI := fmt.Sprintf("postgresql://%s:%s@%s/%s?sslmode=disable", config.PostgresUser, config.PostgresPwd, config.PostgresHost, config.PostgresDBName) dbSession, err = sql.Open("postgres", connectionURI) if err != nil { return nil } err = dbSession.Ping() if err != nil { return nil } return &DatabasePostgreSQL{session: dbSession, schema: config.PostgresDBSchema} } // Ping doesn't use db.Ping because it doesn't Ping after the first time // https://stackoverflow.com/a/41619206/3853913 func (db *DatabasePostgreSQL) Ping() error { _, err := db.session.Query("SELECT WHERE 1=0") return err }