75 lines
2.4 KiB
Go
75 lines
2.4 KiB
Go
// Package settings reads and writes the shared `settings` key/value table, which holds small
|
|
// per-deployment values such as the login-required toggle.
|
|
package settings
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// Value reads one key from the shared `settings` table. An absent or empty
|
|
// setting returns fallback; database errors are returned to the caller.
|
|
func Value(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) {
|
|
var value string
|
|
err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return fallback, nil
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if value == "" {
|
|
return fallback, nil
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
// ValueOrFallback preserves the old fallback-on-error behavior for callers
|
|
// whose API cannot return a read error. New request paths should use Value.
|
|
func ValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
|
|
value, err := Value(ctx, db, key, fallback)
|
|
if err != nil {
|
|
return fallback
|
|
}
|
|
return value
|
|
}
|
|
|
|
// Bool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true,
|
|
// anything else is fallback).
|
|
func Bool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool {
|
|
value := strings.ToLower(strings.TrimSpace(ValueOrFallback(ctx, db, key, "")))
|
|
if value == "" {
|
|
return fallback
|
|
}
|
|
return value == "1" || value == "true" || value == "yes" || value == "on"
|
|
}
|
|
|
|
// Save upserts one key in the shared `settings` table.
|
|
func Save(ctx context.Context, db *pgxpool.Pool, key, value string) error {
|
|
_, err := db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value)
|
|
return err
|
|
}
|
|
|
|
// Migrate creates the settings table and its default login-required row. It is idempotent.
|
|
func Migrate(ctx context.Context, db *pgxpool.Pool) error {
|
|
for _, statement := range migrationStatements {
|
|
if _, err := db.Exec(ctx, statement); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var migrationStatements = []string{
|
|
`CREATE TABLE IF NOT EXISTS settings (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT,
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
)`,
|
|
`INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`,
|
|
}
|