ipld-eth-server/pkg/repositories/postgres/postgres.go
Matt K ed907535e3 Separate DB access into several repos (#28)
* Separate files for InMemory

* Start using separate repos for collaborating objects

* Before Updating schema

* Separate various repos
2018-02-12 10:54:05 -06:00

58 lines
1.5 KiB
Go

package postgres
import (
"errors"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/vulcanize/vulcanizedb/pkg/config"
"github.com/vulcanize/vulcanizedb/pkg/core"
)
type DB struct {
*sqlx.DB
node core.Node
nodeId int64
}
var (
ErrDBInsertFailed = errors.New("postgres: insert failed")
ErrDBDeleteFailed = errors.New("postgres: delete failed")
ErrDBConnectionFailed = errors.New("postgres: db connection failed")
ErrUnableToSetNode = errors.New("postgres: unable to set node")
)
func NewDB(databaseConfig config.Database, node core.Node) (*DB, error) {
connectString := config.DbConnectionString(databaseConfig)
db, err := sqlx.Connect("postgres", connectString)
if err != nil {
return &DB{}, ErrDBConnectionFailed
}
pg := DB{DB: db, node: node}
err = pg.CreateNode(&node)
if err != nil {
return &DB{}, ErrUnableToSetNode
}
return &pg, nil
}
func (db *DB) CreateNode(node *core.Node) error {
var nodeId int64
err := db.QueryRow(
`INSERT INTO nodes (genesis_block, network_id, node_id, client_name)
VALUES ($1, $2, $3, $4)
ON CONFLICT (genesis_block, network_id, node_id)
DO UPDATE
SET genesis_block = $1,
network_id = $2,
node_id = $3,
client_name = $4
RETURNING id`,
node.GenesisBlock, node.NetworkId, node.Id, node.ClientName).Scan(&nodeId)
if err != nil {
return ErrUnableToSetNode
}
db.nodeId = nodeId
return nil
}