Files
radiantwave-legacy/internal/db/newDb.go
T
NeilClack 3cf3e4cf23 Fix database syncronization
When connecting to the internet for the first time, the proclamations table is empty.
If the user navigates to Settings -> Proclamations, then the sync.SyncProclamations
function is called. After this function returns, the ProclamationOptions screen
queries the database for proclamations which returns an empty list. Even though
the database was updated, the ProclamationOptions screen's instance of the database
connection was returning empty.
2026-05-06 10:16:19 -05:00

50 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
}