Last active
March 20, 2020 06:40
-
-
Save mkfeuhrer/09f619de3744830d09a9beae3fd5edbf to your computer and use it in GitHub Desktop.
postgres setup with gorm DB (postgres)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package db | |
import ( | |
"github.com/jinzhu/gorm" | |
) | |
type PostgresStore interface { | |
DB() *gorm.DB | |
Begin() (PostgresStore, error) | |
Commit() error | |
Rollback() error | |
Close() | |
} | |
type postgresStore struct { | |
db *gorm.DB | |
} | |
// Here dbConfig stores DB parameters as configs. | |
// dbconfig.Driver = "postgres", dbConfig.URL() = "postgres://username:password@127.0.0.1:5432/yourDB" | |
func New(dbConfig config.PostgresDBConfig) (*postgresStore, error) { | |
db, err := gorm.Open(dbConfig.Driver, dbConfig.URL()) | |
if err != nil { | |
return nil, err | |
} | |
db.DB().SetMaxIdleConns(0) | |
store := NewStore(db) | |
return store, nil | |
} | |
func NewStore(db *gorm.DB) *postgresStore { | |
store := &postgresStore{db: db} | |
return store | |
} | |
func (s *postgresStore) DB() *gorm.DB { | |
return s.db | |
} | |
func (s *postgresStore) Begin() (PostgresStore, error) { | |
tx := s.db.Begin() | |
if tx.Error != nil { | |
return nil, tx.Error | |
} | |
store := NewStore(tx) | |
return store, nil | |
} | |
func (s *postgresStore) Commit() error { | |
c := s.db.Commit() | |
if c.Error != nil { | |
return c.Error | |
} | |
return nil | |
} | |
func (s *postgresStore) Rollback() error { | |
c := s.db.Rollback() | |
if c.Error != nil { | |
return c.Error | |
} | |
return nil | |
} | |
func (s *postgresStore) Close() { | |
s.db.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment