Files
LektorenPlan/web/store/db.go
T

367 lines
10 KiB
Go

// Package store persists tenants, accounts and planning data in SQLite.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
_ "modernc.org/sqlite"
)
// Common store errors.
var (
ErrNotFound = errors.New("nicht gefunden")
ErrConflict = errors.New("bereits vorhanden")
)
// Store owns the SQLite connection and the application schema.
type Store struct {
db *sql.DB
path string
}
// Open creates the database file if needed and applies the schema.
func Open(path string) (*Store, error) {
dsn := path
if path != ":memory:" && !strings.HasPrefix(path, "file:") {
dsn = "file:" + path
}
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
// A single connection keeps :memory: databases coherent and avoids
// writer contention on small installations.
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
db.SetConnMaxLifetime(0)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pragmas := []string{
"PRAGMA foreign_keys = ON",
"PRAGMA busy_timeout = 5000",
}
for _, pragma := range pragmas {
if _, err := db.ExecContext(ctx, pragma); err != nil {
db.Close()
return nil, fmt.Errorf("configure database: %w", err)
}
}
if path != ":memory:" && !strings.HasPrefix(path, "file::memory:") {
if _, err := db.ExecContext(ctx, "PRAGMA journal_mode = WAL"); err != nil {
db.Close()
return nil, fmt.Errorf("enable WAL: %w", err)
}
}
store := &Store{db: db, path: path}
if err := store.migrate(ctx); err != nil {
db.Close()
return nil, err
}
return store, nil
}
// Close releases the database handle.
func (s *Store) Close() error { return s.db.Close() }
// Path returns the configured database path.
func (s *Store) Path() string { return s.path }
// DB exposes the raw handle for maintenance tasks such as backups.
func (s *Store) DB() *sql.DB { return s.db }
const schema = `
CREATE TABLE IF NOT EXISTS schema_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS tenants (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1,
must_change_password INTEGER NOT NULL DEFAULT 1,
linked_tenant_id TEXT NOT NULL DEFAULT '',
linked_person_id TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS memberships (
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
PRIMARY KEY (user_id, tenant_id)
);
CREATE INDEX IF NOT EXISTS idx_memberships_tenant ON memberships(tenant_id);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
csrf_token TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
CREATE TABLE IF NOT EXISTS churches (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
name TEXT NOT NULL,
short_name TEXT NOT NULL,
symbol TEXT NOT NULL,
color_hex TEXT NOT NULL,
address TEXT NOT NULL DEFAULT '',
sort_index INTEGER NOT NULL DEFAULT 0,
notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id)
);
CREATE TABLE IF NOT EXISTS people (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
roles TEXT NOT NULL,
email TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '',
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
max_per_month INTEGER NOT NULL DEFAULT 6,
active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id)
);
CREATE TABLE IF NOT EXISTS absences (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
person_id TEXT NOT NULL,
start_date TEXT NOT NULL,
end_date TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id)
);
CREATE INDEX IF NOT EXISTS idx_absences_person ON absences(tenant_id, person_id);
CREATE TABLE IF NOT EXISTS service_templates (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
church_id TEXT NOT NULL,
weekday INTEGER NOT NULL,
time_minutes INTEGER NOT NULL,
title TEXT NOT NULL,
lectors_needed INTEGER NOT NULL DEFAULT 1,
helpers_needed INTEGER NOT NULL DEFAULT 1,
valid_from TEXT NOT NULL,
valid_to TEXT,
active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id)
);
CREATE INDEX IF NOT EXISTS idx_templates_church ON service_templates(tenant_id, church_id);
CREATE TABLE IF NOT EXISTS service_exceptions (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
template_id TEXT NOT NULL,
date TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, template_id, date)
);
CREATE TABLE IF NOT EXISTS services (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
church_id TEXT NOT NULL,
location TEXT NOT NULL DEFAULT '',
template_id TEXT,
date TEXT NOT NULL,
time_minutes INTEGER NOT NULL,
title TEXT NOT NULL,
lectors_needed INTEGER NOT NULL DEFAULT 1,
helpers_needed INTEGER NOT NULL DEFAULT 1,
kind TEXT NOT NULL DEFAULT 'regular',
notes TEXT NOT NULL DEFAULT '',
locked INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, id)
);
CREATE INDEX IF NOT EXISTS idx_services_date ON services(tenant_id, date);
CREATE INDEX IF NOT EXISTS idx_services_church ON services(tenant_id, church_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_services_template_date
ON services(tenant_id, template_id, date) WHERE template_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS assignments (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
service_id TEXT NOT NULL,
person_id TEXT NOT NULL,
role TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, service_id, person_id, role)
);
CREATE INDEX IF NOT EXISTS idx_assignments_service ON assignments(tenant_id, service_id);
CREATE INDEX IF NOT EXISTS idx_assignments_person ON assignments(tenant_id, person_id);
CREATE TABLE IF NOT EXISTS liturgical_days (
date TEXT PRIMARY KEY,
title TEXT NOT NULL,
rank TEXT NOT NULL DEFAULT '',
color TEXT NOT NULL DEFAULT 'g',
remark TEXT NOT NULL DEFAULT '',
first_reading TEXT NOT NULL DEFAULT '',
psalm TEXT NOT NULL DEFAULT '',
second_reading TEXT NOT NULL DEFAULT '',
gospel TEXT NOT NULL DEFAULT '',
is_obligation INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS tenant_settings (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (tenant_id, key)
);
`
func (s *Store) migrate(ctx context.Context) error {
if _, err := s.db.ExecContext(ctx, schema); err != nil {
return fmt.Errorf("apply schema: %w", err)
}
// Existing databases predate the password-state and person-link columns.
// CREATE TABLE IF NOT EXISTS does not modify them, so add the columns here.
columns := []struct {
name string
definition string
}{
{"must_change_password", "INTEGER NOT NULL DEFAULT 1"},
{"linked_tenant_id", "TEXT NOT NULL DEFAULT ''"},
{"linked_person_id", "TEXT NOT NULL DEFAULT ''"},
}
for _, column := range columns {
exists, err := s.hasColumn(ctx, "users", column.name)
if err != nil {
return fmt.Errorf("inspect users table: %w", err)
}
if exists {
continue
}
if _, err := s.db.ExecContext(ctx,
"ALTER TABLE users ADD COLUMN "+column.name+" "+column.definition); err != nil {
return fmt.Errorf("add users.%s: %w", column.name, err)
}
}
if _, err := s.db.ExecContext(ctx,
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '2') "+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
return fmt.Errorf("record schema version: %w", err)
}
return nil
}
func (s *Store) hasColumn(ctx context.Context, table, column string) (bool, error) {
rows, err := s.db.QueryContext(ctx, "PRAGMA table_info("+table+")")
if err != nil {
return false, err
}
defer rows.Close()
for rows.Next() {
var cid, notNull, pk int
var name, kind string
var defaultValue sql.NullString
if err := rows.Scan(&cid, &name, &kind, &notNull, &defaultValue, &pk); err != nil {
return false, err
}
if name == column {
return true, nil
}
}
return false, rows.Err()
}
func (s *Store) transaction(ctx context.Context, fn func(*sql.Tx) error) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(tx); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}
func nowText() string { return time.Now().UTC().Format(time.RFC3339) }
func parseTime(value string) time.Time {
t, err := time.Parse(time.RFC3339, value)
if err != nil {
return time.Time{}
}
return t
}
func boolInt(value bool) int {
if value {
return 1
}
return 0
}
func nullString(value *string) any {
if value == nil || strings.TrimSpace(*value) == "" {
return nil
}
return *value
}
func stringValue(value sql.NullString) string {
if value.Valid {
return value.String
}
return ""
}
func intValue(value sql.NullInt64) int {
if value.Valid {
return int(value.Int64)
}
return 0
}
func isUniqueViolation(err error) bool {
if err == nil {
return false
}
text := strings.ToLower(err.Error())
return strings.Contains(text, "unique constraint") || strings.Contains(text, "constraint failed")
}