49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
// Package db provides a database connection and functions for interacting with the database.
|
|
// The DB object should be held and maintained by the application, not by this package.
|
|
// The application should be responsible for connecting to, migrating, and initial population
|
|
// of the database. This package should only provide the schema definitions and helper functions.
|
|
// Schema definitions should clone API response structures as closely as possible.
|
|
|
|
package db
|
|
|
|
import (
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// Connect to the database and return the gorm.DB object.
|
|
func Connect(dbpath string) (*gorm.DB, error) {
|
|
db, err := gorm.Open(sqlite.Open(dbpath), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Set pragmas
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pragmas := []string{
|
|
"PRAGMA journal_mode=WAL",
|
|
"PRAGMA synchronous=FULL",
|
|
"PRAGMA foreign_keys=ON",
|
|
"PRAGMA busy_timeout=5000",
|
|
}
|
|
|
|
for _, pragma := range pragmas {
|
|
if _, err := sqlDB.Exec(pragma); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return db, nil
|
|
}
|
|
|
|
// Migrate the database schema
|
|
func Migrate(db *gorm.DB) error {
|
|
// Pass all models to be migrated to this function call.
|
|
if err := db.AutoMigrate(&AppConfig{}, &Log{}, &Proclamation{}, &ProclamationCategory{}); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|