Notes2/db.go
2024-11-27 21:41:48 +01:00

64 lines
1.2 KiB
Go

package main
import (
// External
"git.gibonuddevalla.se/go/dbschema"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
// Standard
"fmt"
)
var (
db *sqlx.DB
)
func sqlCallback(db string, version int) (sql []byte, found bool) { // {{{
var err error
fname := fmt.Sprintf("sql/%05d.sql", version)
sql, err = SqlFS.ReadFile(fname)
found = (err == nil)
return
} // }}}
func logCallback(section, message string) { // {{{
Log.Info("database", section, message)
} // }}}
func initDB() (err error) { // {{{
dbConn := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
config.Database.Host,
config.Database.Port,
config.Database.Username,
config.Database.Password,
config.Database.Db,
)
Log.Info(
"database",
"host", config.Database.Host,
"port", config.Database.Port,
)
if db, err = sqlx.Connect("postgres", dbConn); err != nil {
return
}
upgrader := dbschema.NewUpgrader()
upgrader.SetSqlCallback(sqlCallback)
upgrader.SetLogCallback(logCallback)
_, err = upgrader.AddDatabase(
config.Database.Host,
config.Database.Port,
config.Database.Db,
config.Database.Username,
config.Database.Password,
)
if err != nil {
return
}
err = upgrader.Run()
return
} // }}}