Files
LektorenPlan/web/store/db.go
T

475 lines
14 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 '',
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)
);
CREATE TABLE IF NOT EXISTS dispatch_preferences (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
person_id TEXT NOT NULL,
channel TEXT NOT NULL DEFAULT 'email',
variant TEXT NOT NULL DEFAULT 'compact',
cover INTEGER NOT NULL DEFAULT 1,
updated_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, person_id)
);
CREATE TABLE IF NOT EXISTS dispatch_log (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
batch_id TEXT NOT NULL,
range_start TEXT NOT NULL,
range_end TEXT NOT NULL,
person_id TEXT NOT NULL DEFAULT '',
person_name TEXT NOT NULL DEFAULT '',
channel TEXT NOT NULL,
variant TEXT NOT NULL DEFAULT '',
cover INTEGER NOT NULL DEFAULT 0,
email TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_dispatch_log_tenant ON dispatch_log(tenant_id, created_at);
CREATE TABLE IF NOT EXISTS user_keys (
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
kdf_salt BLOB NOT NULL,
kdf_version TEXT NOT NULL,
public_key BLOB NOT NULL,
wrapped_private BLOB NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS key_wrappers (
scope_type TEXT NOT NULL,
tenant_id TEXT NOT NULL,
scope_id TEXT NOT NULL,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
ephemeral_public BLOB NOT NULL,
wrapped_dek BLOB NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (scope_type, tenant_id, scope_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_key_wrappers_user ON key_wrappers(user_id);
CREATE TABLE IF NOT EXISTS secrets (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
scope_type TEXT NOT NULL,
scope_id TEXT NOT NULL,
secret_key TEXT NOT NULL,
ciphertext BLOB NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, scope_type, scope_id, secret_key)
);
CREATE TABLE IF NOT EXISTS secret_state (
tenant_id TEXT PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
initialized_at TEXT NOT NULL
);
`
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', '5') "+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
return fmt.Errorf("record schema version: %w", err)
}
// Phone numbers are no longer stored anywhere in the web app. Remove both
// the encrypted values and the legacy plaintext column.
if _, err := s.db.ExecContext(ctx,
"DELETE FROM secrets WHERE secret_key='phone'"); err != nil {
return fmt.Errorf("remove encrypted phone numbers: %w", err)
}
hasPhone, err := s.hasColumn(ctx, "people", "phone")
if err != nil {
return fmt.Errorf("inspect people table: %w", err)
}
if hasPhone {
if _, err := s.db.ExecContext(ctx, "ALTER TABLE people DROP COLUMN phone"); err != nil {
return fmt.Errorf("drop people.phone: %w", err)
}
}
// Editors and linked readers hold key material; administrators never do.
// Readers may only keep the scope of their linked person.
if _, err := s.db.ExecContext(ctx,
"DELETE FROM key_wrappers WHERE user_id IN (SELECT id FROM users WHERE role='admin')"); err != nil {
return fmt.Errorf("prune administrator key wrappers: %w", err)
}
if _, err := s.db.ExecContext(ctx,
"DELETE FROM user_keys WHERE user_id IN (SELECT id FROM users WHERE role='admin')"); err != nil {
return fmt.Errorf("prune administrator keys: %w", err)
}
if _, err := s.db.ExecContext(ctx, `
DELETE FROM key_wrappers WHERE user_id IN (
SELECT u.id FROM users u WHERE u.role='reader' AND (
u.linked_tenant_id='' OR u.linked_person_id='' OR NOT (
key_wrappers.scope_type='person'
AND key_wrappers.tenant_id=u.linked_tenant_id
AND key_wrappers.scope_id=u.linked_person_id
)
)
)`); err != nil {
return fmt.Errorf("prune unlinked reader key wrappers: %w", err)
}
// Dispatch logs used to contain the full recipient address. Remove that
// plaintext now that addresses are stored encrypted.
if _, err := s.db.ExecContext(ctx,
"UPDATE dispatch_log SET email='' WHERE email<>''"); err != nil {
return fmt.Errorf("redact dispatch log: %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")
}