Database is more usable now. All pages have been updated to use the database, and share an application configuration. Page Stack has been removed, no more pages hanging around in memory. Replaced with a 'Router' which uses an Enum to determine which page should be displayed, destroys the old page and initializes the new page all in one go. No more push, pop, rollback, etc. No more holding instances of pages. Logger has been updated with proper timestamps and sorting now works as expected."
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{}); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|