advsql/db.go

68 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-07-05 12:38:39 +02:00
package advsql
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type Database struct {
db *sql.DB
stmts map[string]*sql.Stmt
2022-07-05 12:38:39 +02:00
}
func InitDatabase(database *Database, conn *sql.DB) {
panicOnNil(database)
*database = Database{
db: conn,
stmts: map[string]*sql.Stmt{},
2022-07-08 22:09:53 +02:00
}
database.init()
2022-07-08 22:09:53 +02:00
}
func InitMysqlDatabase(database *Database, host string, port uint16, user, pass, db string) {
panicOnNil(database)
2022-07-05 12:38:39 +02:00
conn, err := sql.Open("mysql", connString(host, port, user, pass, db))
if err != nil {
panic(err)
2022-07-05 12:38:39 +02:00
}
InitDatabase(database, conn)
}
func panicOnNil(database *Database) {
if database == nil {
panic("database is nil. initialize database variable with new()")
}
2022-07-05 12:38:39 +02:00
}
func (db *Database) init() {
for _, globalQuery := range globalStmts {
if db == globalQuery.db {
db.stmt(globalQuery.query)
}
}
}
func (db *Database) stmt(query string) *sql.Stmt {
if stmt, ok := db.stmts[query]; ok {
return stmt
}
stmt, err := db.db.Prepare(query)
2022-07-05 12:38:39 +02:00
if err != nil {
panic(err)
2022-07-05 12:38:39 +02:00
}
db.stmts[query] = stmt
return stmt
2022-07-05 12:38:39 +02:00
}
func (db *Database) Close() error {
for _, stmt := range db.stmts {
stmt.Close()
2022-07-05 12:38:39 +02:00
}
return db.db.Close()
}