2023-03-09 07:48:13 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
/*
|
|
|
|
This database has been based off of openfusion's. Databases should be completely interchangable between
|
|
|
|
openfusion and gopenfusion.
|
|
|
|
*/
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
_ "embed"
|
|
|
|
"fmt"
|
|
|
|
|
2023-12-03 04:09:11 +00:00
|
|
|
"github.com/CPunch/gopenfusion/internal/config"
|
2023-06-22 06:53:38 +00:00
|
|
|
_ "github.com/lib/pq"
|
2023-03-09 07:48:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type DBHandler struct {
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
//go:embed migrations/new.sql
|
|
|
|
var createDBQuery string
|
|
|
|
|
2023-11-21 19:58:59 +00:00
|
|
|
func OpenFromConnectionString(driverName, connectionString string) (*DBHandler, error) {
|
|
|
|
db, err := sql.Open(driverName, connectionString)
|
2023-03-09 07:48:13 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &DBHandler{db}, nil
|
|
|
|
}
|
|
|
|
|
2023-11-21 19:58:59 +00:00
|
|
|
func OpenPostgresDB(dbAddr string) (*DBHandler, error) {
|
|
|
|
fmt := fmt.Sprintf("postgresql://%s:%s@%s/%s?sslmode=disable", config.GetDBUser(), config.GetDBPass(), dbAddr, config.GetDBName())
|
|
|
|
return OpenFromConnectionString("postgres", fmt)
|
|
|
|
}
|
|
|
|
|
2023-03-09 07:48:13 +00:00
|
|
|
func (db *DBHandler) Query(query string, args ...any) (*sql.Rows, error) {
|
|
|
|
return db.db.Query(query, args...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *DBHandler) Exec(query string, args ...any) (sql.Result, error) {
|
|
|
|
return db.db.Exec(query, args...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *DBHandler) Close() error {
|
|
|
|
return db.db.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *DBHandler) Setup() error {
|
|
|
|
// create db tables
|
|
|
|
_, err := db.db.Exec(createDBQuery)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// calls transaction, if transaction returns a non-nil error the transaction is rolled back. otherwise the transaction is committed
|
|
|
|
func (db *DBHandler) Transaction(transaction func(*sql.Tx) error) (err error) {
|
|
|
|
tx, err := db.db.Begin()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if p := recover(); p != nil {
|
|
|
|
// we panic'd ??? rollback and rethrow
|
|
|
|
tx.Rollback()
|
|
|
|
panic(p)
|
|
|
|
} else if err != nil {
|
|
|
|
tx.Rollback()
|
|
|
|
} else {
|
|
|
|
err = tx.Commit()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
err = transaction(tx)
|
|
|
|
return
|
|
|
|
}
|