Adding the factory method to derive postgres implementation for db

This commit is contained in:
Arpit Mohan 2019-02-22 10:16:46 +05:30
parent 6560d1005c
commit f72597051c
4 changed files with 32 additions and 10 deletions

View File

@ -0,0 +1,10 @@
package db
// StorageType is the enum which defines the list of supported databases
type StorageType int
const (
PostgresDb StorageType = iota
MysqlDb
MongoDb
)

View File

@ -7,10 +7,10 @@ type QueryInterface interface {
// ConnectionInterface defines the interface that all db implementations must implement.
type ConnectionInterface interface {
InitDb()
InitDb() error
}
type GoFitDb struct {
type jdbcDb struct {
Dbhost string
Dbport string
Dbuser string
@ -18,3 +18,16 @@ type GoFitDb struct {
Dbname string
MaxOpenConnections int
}
type postgresDb jdbcDb
// NewDb returns an instance of the type of database that must be instantiated. For each new database type
// it must implement the ConnectionInterface and the QueryInterface
func NewDb(storageType StorageType) ConnectionInterface {
switch storageType {
case PostgresDb:
return &postgresDb{}
default:
return nil
}
}

View File

@ -19,9 +19,7 @@ const (
)
// InitDb initializes the database
func (d *GoFitDb) InitDb() {
var err error
func (d *postgresDb) InitDb() (err error) {
// Initialize the database
d.dbConfig()
@ -34,20 +32,21 @@ func (d *GoFitDb) InitDb() {
db, err = sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
return err
}
// Setup connection pool
db.SetMaxOpenConns(d.MaxOpenConnections)
err = db.Ping()
if err != nil {
panic(err)
return err
}
fmt.Println("Successfully connected!")
listTables()
return nil
}
func (d *GoFitDb) dbConfig() {
func (d *postgresDb) dbConfig() {
var ok bool
d.Dbhost, ok = os.LookupEnv(dbhost)
if !ok {

View File

@ -10,8 +10,8 @@ import (
)
func main() {
goFitDb := db.GoFitDb{}
goFitDb.InitDb()
db := db.NewDb(db.PostgresDb)
db.InitDb()
router := httprouter.New()