45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
package data
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"os"
|
|
"strings"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
// applySchema reads schema.sql from the current working directory and executes it.
|
|
// If the file cannot be read, it falls back to a minimal schema that matches tests.
|
|
func applySchema(ctx context.Context, db *sql.DB) error {
|
|
b, err := os.ReadFile("schema.sql")
|
|
if err != nil {
|
|
// Fallback: minimal schema needed for users/roles used by tests.
|
|
b = []byte(`
|
|
PRAGMA foreign_keys = ON;
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id TEXT PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
type TEXT NOT NULL CHECK (type IN ('human','system')),
|
|
pwd_hash TEXT NOT NULL,
|
|
totp_secret TEXT,
|
|
created_at INTEGER NOT NULL,
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS roles (name TEXT PRIMARY KEY);
|
|
CREATE TABLE IF NOT EXISTS user_roles (
|
|
user_id TEXT NOT NULL,
|
|
role TEXT NOT NULL,
|
|
PRIMARY KEY (user_id, role)
|
|
);
|
|
`)
|
|
}
|
|
stmts := strings.TrimSpace(string(b))
|
|
if stmts == "" {
|
|
return errors.New("empty schema")
|
|
}
|
|
_, err = db.ExecContext(ctx, stmts)
|
|
return err
|
|
}
|