Adding the factory method to derive postgres implementation for db
This commit is contained in:
parent
6560d1005c
commit
f72597051c
10
app/server/src/db/constants.go
Normal file
10
app/server/src/db/constants.go
Normal 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
|
||||
)
|
||||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
goFitDb := db.GoFitDb{}
|
||||
goFitDb.InitDb()
|
||||
db := db.NewDb(db.PostgresDb)
|
||||
db.InitDb()
|
||||
|
||||
router := httprouter.New()
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user