first implementation of document strategy

This commit is contained in:
venture
2026-11-13 21:11:28 +01:00
parent fdb52d1cfe
commit 4da2fe9424
19 changed files with 1403 additions and 284 deletions
+68 -20
View File
@@ -4,6 +4,7 @@ import (
"database/sql"
"embed"
"errors"
"fmt"
"regexp"
"strings"
@@ -13,8 +14,10 @@ import (
)
type DatabaseClient struct {
DB *sql.DB
Queries *Queries
DB *sql.DB
WriteDB *sql.DB
Queries *Queries
WriteQueries *Queries
}
// content holds migrations files ( embeded into the go program )
@@ -26,6 +29,8 @@ type NewDatabaseParams struct {
DatabaseName *string
}
var databaseNamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`)
func NewDatabase(params NewDatabaseParams) (error, *DatabaseClient) {
databaseName := "database"
@@ -34,54 +39,97 @@ func NewDatabase(params NewDatabaseParams) (error, *DatabaseClient) {
databaseName = *params.DatabaseName
}
err, normalizedDatabaseName := normalizeDatabaseName(databaseName)
normalizedDatabaseName, err := normalizeDatabaseName(databaseName)
if err != nil {
return err, nil
}
db, err := sql.Open("sqlite", "./"+normalizedDatabaseName+".db")
readDB, err := openSQLite(normalizedDatabaseName, 10)
if err != nil {
return err, nil
}
// setup database
writeDB, err := openSQLite(normalizedDatabaseName, 1)
if err != nil {
_ = readDB.Close()
return err, nil
}
goose.SetBaseFS(embedMigrations)
if err := goose.SetDialect("sqlite3"); err != nil {
panic(err)
_ = readDB.Close()
_ = writeDB.Close()
return err, nil
}
if err := goose.Up(db, "migrations"); err != nil {
panic(err)
if err := goose.Up(writeDB, "migrations"); err != nil {
_ = readDB.Close()
_ = writeDB.Close()
return err, nil
}
return nil, &DatabaseClient{
DB: db,
Queries: New(db),
DB: readDB,
WriteDB: writeDB,
Queries: New(readDB),
WriteQueries: New(writeDB),
}
}
func normalizeDatabaseName(databaseName string) (error, string) {
func (c *DatabaseClient) Close() error {
var errs []error
t := strings.TrimSpace(databaseName)
if c.WriteDB != nil {
errs = append(errs, c.WriteDB.Close())
}
l := strings.ToLower(t)
if c.DB != nil {
errs = append(errs, c.DB.Close())
}
pattern := "[a-zA-Z]+"
return errors.Join(errs...)
}
re, err := regexp.Compile(pattern)
// openSQLite ouvre une connexion avec les PRAGMAs requis. Ils sont passés par
// le DSN car database/sql ouvre plusieurs connexions et qu'un PRAGMA exécuté
// dans une migration goose (transaction) est sans effet.
func openSQLite(databaseName string, maxOpenConns int) (*sql.DB, error) {
dsn := fmt.Sprintf(
"file:%s.db?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)",
databaseName,
)
db, err := sql.Open("sqlite", dsn)
if err != nil {
return err, ""
return nil, err
}
s := re.MatchString(l)
db.SetMaxOpenConns(maxOpenConns)
db.SetMaxIdleConns(maxOpenConns)
if s == false {
return errors.New(databaseName + " doesn't follow the pattern " + pattern), ""
if err := db.Ping(); err != nil {
_ = db.Close()
return nil, fmt.Errorf("ouverture de %s.db : %w", databaseName, err)
}
return nil, l
return db, nil
}
func normalizeDatabaseName(databaseName string) (string, error) {
trimmed := strings.TrimSpace(databaseName)
if !databaseNamePattern.MatchString(trimmed) {
return "", fmt.Errorf(
"nom de base invalide %q : attendu ^[a-zA-Z][a-zA-Z0-9_]*$",
databaseName,
)
}
return strings.ToLower(trimmed), nil
}
+198
View File
@@ -0,0 +1,198 @@
package database
import (
"context"
"encoding/hex"
"testing"
"time"
"mediarr/ident"
"github.com/pressly/goose/v3"
)
func TestNewDatabase(t *testing.T) {
t.Chdir(t.TempDir())
err, client := NewDatabase(NewDatabaseParams{})
if err != nil {
t.Fatalf("NewDatabase : %v", err)
}
defer client.Close()
ctx := context.Background()
var foreignKeys int
if err := client.DB.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&foreignKeys); err != nil {
t.Fatalf("PRAGMA foreign_keys : %v", err)
}
if foreignKeys != 1 {
t.Fatalf("foreign_keys = %d, attendu 1", foreignKeys)
}
var journalMode string
if err := client.DB.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&journalMode); err != nil {
t.Fatalf("PRAGMA journal_mode : %v", err)
}
if journalMode != "wal" {
t.Fatalf("journal_mode = %q, attendu wal", journalMode)
}
var busyTimeout int
if err := client.DB.QueryRowContext(ctx, "PRAGMA busy_timeout").Scan(&busyTimeout); err != nil {
t.Fatalf("PRAGMA busy_timeout : %v", err)
}
if busyTimeout != 5000 {
t.Fatalf("busy_timeout = %d, attendu 5000", busyTimeout)
}
var synchronous int
if err := client.DB.QueryRowContext(ctx, "PRAGMA synchronous").Scan(&synchronous); err != nil {
t.Fatalf("PRAGMA synchronous : %v", err)
}
if synchronous != 1 {
t.Fatalf("synchronous = %d, attendu 1 (NORMAL)", synchronous)
}
systemID := ident.MustParse("00000000-0000-7000-8000-000000000001")
system, err := client.Queries.GetPrincipal(ctx, systemID)
if err != nil {
t.Fatalf("GetPrincipal(system) : %v", err)
}
if system.Kind != "system" {
t.Fatalf("kind = %q, attendu system", system.Kind)
}
adminsID := ident.MustParse("00000000-0000-7000-8000-000000000002")
_, err = client.WriteQueries.CreateMembership(ctx, CreateMembershipParams{
GroupID: adminsID,
MemberID: adminsID,
Role: "member",
CreatedAt: time.Now().UnixMilli(),
})
if err == nil {
t.Fatal("membership invalide (groupe dans groupe) acceptée")
}
policyID := ident.MustParse("00000000-0000-7000-8000-000000000101")
rootID, err := ident.NewV7()
if err != nil {
t.Fatal(err)
}
rootPath := hex.EncodeToString(rootID.Bytes()) + "/"
insertDocument(ctx, t, client, rootID, "library", nil, "Films", rootPath, 0, &policyID, "CLUSTER")
childID, err := ident.NewV7()
if err != nil {
t.Fatal(err)
}
childPath := rootPath + hex.EncodeToString(childID.Bytes()) + "/"
insertDocument(ctx, t, client, childID, "folder", &rootID, "Action", childPath, 1, nil, "")
badPathID, err := ident.NewV7()
if err != nil {
t.Fatal(err)
}
badPath := "/deadbeef/" + hex.EncodeToString(badPathID.Bytes()) + "/"
if insertDocumentErr(ctx, client, badPathID, "folder", &rootID, "Bad", badPath, 1, nil, "") == nil {
t.Fatal("document avec path incohérent accepté")
}
badDepthID, err := ident.NewV7()
if err != nil {
t.Fatal(err)
}
badDepthPath := rootPath + hex.EncodeToString(badDepthID.Bytes()) + "/"
if insertDocumentErr(ctx, client, badDepthID, "folder", &rootID, "Bad", badDepthPath, 5, nil, "") == nil {
t.Fatal("document avec profondeur incohérente accepté")
}
}
func insertDocument(
ctx context.Context,
t *testing.T,
client *DatabaseClient,
id ident.UUID,
kind string,
parentID *ident.UUID,
name string,
path string,
depth int,
policyID *ident.UUID,
visibility string,
) {
t.Helper()
if err := insertDocumentErr(ctx, client, id, kind, parentID, name, path, depth, policyID, visibility); err != nil {
t.Fatalf("insertion document %q : %v", name, err)
}
}
func insertDocumentErr(
ctx context.Context,
client *DatabaseClient,
id ident.UUID,
kind string,
parentID *ident.UUID,
name string,
path string,
depth int,
policyID *ident.UUID,
visibility string,
) error {
var visibilityValue any
if visibility != "" {
visibilityValue = visibility
}
_, err := client.WriteDB.ExecContext(ctx, `
INSERT INTO document (
id, kind, owner_id, created_by, parent_id, name, name_key, path, depth,
policy_id, visibility, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
id,
kind,
ident.MustParse("00000000-0000-7000-8000-000000000001"),
ident.MustParse("00000000-0000-7000-8000-000000000001"),
parentID,
name,
name,
path,
depth,
policyID,
visibilityValue,
time.Now().UnixMilli(),
time.Now().UnixMilli(),
)
return err
}
func TestMigrationsDown(t *testing.T) {
t.Chdir(t.TempDir())
err, client := NewDatabase(NewDatabaseParams{})
if err != nil {
t.Fatalf("NewDatabase : %v", err)
}
defer client.Close()
if err := goose.DownTo(client.WriteDB, "migrations", 0); err != nil {
t.Fatalf("goose DownTo : %v", err)
}
var count int
err = client.DB.QueryRowContext(
context.Background(),
"SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'document'",
).Scan(&count)
if err != nil {
t.Fatalf("inspection sqlite_master : %v", err)
}
if count != 0 {
t.Fatal("la table document existe encore après le rollback")
}
}
-5
View File
@@ -1,5 +0,0 @@
-- +goose Up
SELECT 'up SQL query';
-- +goose Down
SELECT 'down SQL query';
+323
View File
@@ -0,0 +1,323 @@
-- +goose Up
-- =====================================================================
-- NOYAU POC : tables et index
-- =====================================================================
-- Cible : SQLite >= 3.37 (tables STRICT), JSON1 intégré (>= 3.38)
-- Connexion : les PRAGMAs sont appliqués par le DSN (voir database.go) :
-- foreign_keys = ON, journal_mode = WAL,
-- synchronous = NORMAL, busy_timeout = 5000
-- Un seul écrivain (WriteDB), plusieurs lecteurs (DB).
-- Conventions
-- - Identifiants : UUIDv7 en BLOB de 16 octets (sauf amorçages).
-- - Dates : entier, millisecondes Unix UTC.
-- - JSON : TEXT validé par CHECK (json_valid(...)).
-- - Hash : BLOB multihash (BLAKE3).
-- - Suppression : deleted_at (corbeille), jamais de purge immédiate.
-- =====================================================================
-- ---------------------------------------------------------------------
-- 1. IDENTITÉS ET GROUPES
-- ---------------------------------------------------------------------
CREATE TABLE principal (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
kind TEXT NOT NULL CHECK (kind IN ('cluster','user','guest','group','system')),
name TEXT NOT NULL CHECK (length(name) > 0),
public_key BLOB,
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active','disabled','revoked')),
successor_id BLOB REFERENCES principal(id),
created_at INTEGER NOT NULL,
disabled_at INTEGER,
CHECK (kind <> 'cluster' OR public_key IS NOT NULL),
CHECK (successor_id IS NULL OR successor_id <> id)
) STRICT;
CREATE UNIQUE INDEX principal_name ON principal(kind, name) WHERE status <> 'revoked';
CREATE UNIQUE INDEX principal_single_cluster ON principal(kind) WHERE kind = 'cluster';
CREATE INDEX principal_successor ON principal(successor_id) WHERE successor_id IS NOT NULL;
CREATE TABLE membership (
group_id BLOB NOT NULL CHECK (length(group_id) = 16) REFERENCES principal(id) ON DELETE CASCADE,
member_id BLOB NOT NULL CHECK (length(member_id) = 16) REFERENCES principal(id) ON DELETE CASCADE,
role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('member','admin')),
created_at INTEGER NOT NULL,
PRIMARY KEY (group_id, member_id)
) STRICT, WITHOUT ROWID;
CREATE INDEX membership_member ON membership(member_id);
-- ---------------------------------------------------------------------
-- 2. COMPTES ET SESSIONS
-- ---------------------------------------------------------------------
CREATE TABLE account (
principal_id BLOB PRIMARY KEY CHECK (length(principal_id) = 16)
REFERENCES principal(id) ON DELETE CASCADE,
login TEXT NOT NULL CHECK (length(login) > 0),
login_key TEXT NOT NULL CHECK (length(login_key) > 0),
password_hash TEXT,
password_changed_at INTEGER,
must_change_password INTEGER NOT NULL DEFAULT 0 CHECK (must_change_password IN (0,1)),
state TEXT NOT NULL DEFAULT 'active' CHECK (state IN ('active','locked','disabled')),
failed_attempts INTEGER NOT NULL DEFAULT 0 CHECK (failed_attempts >= 0),
locked_until INTEGER,
last_login_at INTEGER,
created_at INTEGER NOT NULL
) STRICT;
CREATE UNIQUE INDEX account_login_key ON account(login_key);
CREATE TABLE session (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
token_hash BLOB NOT NULL UNIQUE CHECK (length(token_hash) = 32),
principal_id BLOB NOT NULL CHECK (length(principal_id) = 16)
REFERENCES principal(id) ON DELETE CASCADE,
kind TEXT NOT NULL DEFAULT 'web' CHECK (kind IN ('web','api')),
label TEXT,
user_agent TEXT,
ip_prefix TEXT,
created_at INTEGER NOT NULL,
last_seen_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
idle_expires_at INTEGER NOT NULL,
revoked_at INTEGER
) STRICT;
CREATE INDEX session_principal ON session(principal_id) WHERE revoked_at IS NULL;
CREATE INDEX session_expiry ON session(expires_at);
-- ---------------------------------------------------------------------
-- 3. TYPES, POLITIQUES, MAGASIN DE BLOBS
-- ---------------------------------------------------------------------
CREATE TABLE document_kind (
kind TEXT PRIMARY KEY,
provider TEXT NOT NULL DEFAULT 'core',
has_content INTEGER NOT NULL CHECK (has_content IN (0,1)),
hidden INTEGER NOT NULL DEFAULT 0 CHECK (hidden IN (0,1)),
metadata_schema TEXT CHECK (metadata_schema IS NULL OR json_valid(metadata_schema))
) STRICT;
CREATE TABLE storage_policy (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
name TEXT NOT NULL UNIQUE,
mode TEXT NOT NULL CHECK (mode IN ('cloud','sync')),
min_remote_replicas INTEGER NOT NULL DEFAULT 0 CHECK (min_remote_replicas >= 0),
replicate_history INTEGER NOT NULL DEFAULT 0 CHECK (replicate_history IN (0,1)),
cache_ttl_s INTEGER CHECK (cache_ttl_s IS NULL OR cache_ttl_s >= 0),
cache_max_bytes INTEGER CHECK (cache_max_bytes IS NULL OR cache_max_bytes >= 0),
version_retention TEXT NOT NULL
DEFAULT '{"keep_all_days":30,"keep_daily_days":0,"keep_monthly":0}'
CHECK (json_valid(version_retention)),
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE storage_backend (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
kind TEXT NOT NULL CHECK (kind IN ('hub_fs','s3','peer')),
name TEXT NOT NULL UNIQUE,
config TEXT NOT NULL CHECK (json_valid(config)),
secret_ref TEXT,
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0,1)),
capacity_bytes INTEGER CHECK (capacity_bytes IS NULL OR capacity_bytes >= 0),
state TEXT NOT NULL DEFAULT 'unknown'
CHECK (state IN ('unknown','ok','degraded','failing')),
last_ok_at INTEGER,
last_error TEXT,
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE blob (
root BLOB PRIMARY KEY CHECK (length(root) > 0),
size INTEGER NOT NULL CHECK (size >= 0),
state TEXT NOT NULL CHECK (state IN ('partial','present','corrupt')),
role TEXT NOT NULL DEFAULT 'authoritative' CHECK (role IN ('authoritative','cache')),
unit_size INTEGER NOT NULL DEFAULT 1048576 CHECK (unit_size > 0),
have BLOB,
tree_state TEXT NOT NULL DEFAULT 'none' CHECK (tree_state IN ('none','building','ready')),
encryption TEXT NOT NULL DEFAULT 'none' CHECK (encryption IN ('none','client_v1')),
last_verified_at INTEGER,
verify_error TEXT,
last_access_at INTEGER,
created_at INTEGER NOT NULL
) STRICT;
CREATE INDEX blob_state ON blob(state) WHERE state <> 'present';
CREATE INDEX blob_cache ON blob(last_access_at) WHERE role = 'cache';
CREATE INDEX blob_verify ON blob(last_verified_at) WHERE state = 'present';
CREATE TABLE blob_location (
root BLOB NOT NULL REFERENCES blob(root) ON DELETE CASCADE,
backend_id BLOB NOT NULL CHECK (length(backend_id) = 16) REFERENCES storage_backend(id),
locator TEXT NOT NULL CHECK (length(locator) > 0),
state TEXT NOT NULL CHECK (state IN ('present','pending_delete','missing')),
created_at INTEGER NOT NULL,
PRIMARY KEY (root, backend_id),
UNIQUE (backend_id, locator)
) STRICT, WITHOUT ROWID;
CREATE INDEX blob_location_backend ON blob_location(backend_id);
CREATE TABLE staging_item (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
origin TEXT NOT NULL CHECK (origin IN ('import','upload','relay_cache')),
job_ref TEXT,
locator TEXT NOT NULL CHECK (length(locator) > 0),
size INTEGER CHECK (size IS NULL OR size >= 0),
state TEXT NOT NULL CHECK (state IN ('staged','hashing','committed','discarded')),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE INDEX staging_state ON staging_item(state, updated_at);
-- ---------------------------------------------------------------------
-- 4. DOCUMENTS ET VERSIONS
-- ---------------------------------------------------------------------
CREATE TABLE document (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
kind TEXT NOT NULL REFERENCES document_kind(kind),
owner_id BLOB NOT NULL REFERENCES principal(id),
created_by BLOB NOT NULL REFERENCES principal(id),
parent_id BLOB REFERENCES document(id),
name TEXT NOT NULL CHECK (length(name) > 0 AND instr(name, '/') = 0),
name_key TEXT NOT NULL CHECK (length(name_key) > 0),
path TEXT NOT NULL CHECK (path = lower(path)),
depth INTEGER NOT NULL CHECK (depth >= 0),
position TEXT,
head_version_id BLOB REFERENCES document_version(id) DEFERRABLE INITIALLY DEFERRED,
metadata TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(metadata)),
policy_id BLOB REFERENCES storage_policy(id),
visibility TEXT CHECK (visibility IN ('PRIVATE','CLUSTER','FEDERATED','PUBLIC')),
acl_inherit INTEGER NOT NULL DEFAULT 1 CHECK (acl_inherit IN (0,1)),
rev INTEGER NOT NULL DEFAULT 1 CHECK (rev > 0),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
deleted_at INTEGER,
deleted_by BLOB REFERENCES principal(id),
trash_batch BLOB,
CHECK ((parent_id IS NULL) = (depth = 0)),
CHECK (path LIKE '%' || lower(hex(id)) || '/'),
CHECK (parent_id IS NOT NULL OR path = lower(hex(id)) || '/'),
CHECK (parent_id IS NOT NULL OR kind = 'library'),
CHECK (parent_id IS NOT NULL OR (visibility IS NOT NULL AND policy_id IS NOT NULL)),
CHECK (parent_id IS NULL OR parent_id <> id)
) STRICT;
CREATE TABLE document_version (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
document_id BLOB NOT NULL REFERENCES document(id),
seq INTEGER NOT NULL CHECK (seq > 0),
content_root BLOB NOT NULL CHECK (length(content_root) > 0),
size INTEGER NOT NULL CHECK (size >= 0),
mime TEXT,
author_id BLOB NOT NULL REFERENCES principal(id),
device_id BLOB,
origin TEXT NOT NULL CHECK (origin IN ('upload','import','merge','restore','system')),
message TEXT,
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0,1)),
content_purged_at INTEGER,
created_at INTEGER NOT NULL,
UNIQUE (document_id, seq)
) STRICT;
CREATE UNIQUE INDEX doc_sibling_name
ON document(ifnull(parent_id, zeroblob(16)), name_key) WHERE deleted_at IS NULL;
CREATE INDEX doc_path ON document(path);
CREATE INDEX doc_parent ON document(parent_id, position, name_key) WHERE deleted_at IS NULL;
CREATE INDEX doc_owner ON document(owner_id);
CREATE INDEX doc_kind ON document(kind);
CREATE INDEX doc_trash ON document(trash_batch) WHERE trash_batch IS NOT NULL;
CREATE INDEX doc_head ON document(head_version_id);
CREATE INDEX doc_created_by ON document(created_by);
CREATE INDEX version_doc ON document_version(document_id, seq DESC);
CREATE INDEX version_blob ON document_version(content_root);
CREATE INDEX version_author ON document_version(author_id);
-- ---------------------------------------------------------------------
-- 5. DROITS
-- ---------------------------------------------------------------------
CREATE TABLE acl_entry (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
document_id BLOB NOT NULL REFERENCES document(id),
subject_id BLOB NOT NULL REFERENCES principal(id),
permissions INTEGER NOT NULL CHECK (permissions BETWEEN 1 AND 127),
propagate INTEGER NOT NULL DEFAULT 1 CHECK (propagate IN (0,1)),
expires_at INTEGER,
granted_by BLOB NOT NULL REFERENCES principal(id),
created_at INTEGER NOT NULL,
revoked_at INTEGER,
UNIQUE (document_id, subject_id)
) STRICT;
CREATE INDEX acl_doc ON acl_entry(document_id) WHERE revoked_at IS NULL;
CREATE INDEX acl_subject ON acl_entry(subject_id) WHERE revoked_at IS NULL;
CREATE TABLE library_config (
document_id BLOB PRIMARY KEY REFERENCES document(id),
protection TEXT NOT NULL DEFAULT 'server' CHECK (protection IN ('server','vault')),
admin_visible INTEGER NOT NULL DEFAULT 0 CHECK (admin_visible IN (0,1)),
created_at INTEGER NOT NULL
) STRICT;
-- ---------------------------------------------------------------------
-- 6. EXPORT VERS JELLYFIN
-- ---------------------------------------------------------------------
CREATE TABLE export_target (
id BLOB PRIMARY KEY CHECK (length(id) = 16),
library_id BLOB NOT NULL REFERENCES document(id),
root_path TEXT NOT NULL CHECK (length(root_path) > 0),
mode TEXT NOT NULL DEFAULT 'hardlink' CHECK (mode IN ('hardlink','symlink','copy')),
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0,1)),
check_state TEXT NOT NULL DEFAULT 'unchecked' CHECK (check_state IN ('unchecked','ok','failed')),
last_check_at INTEGER,
last_error TEXT,
consent_by BLOB REFERENCES principal(id),
UNIQUE (library_id, root_path)
) STRICT;
CREATE INDEX export_target_library ON export_target(library_id);
CREATE TABLE export_link (
target_id BLOB NOT NULL REFERENCES export_target(id) ON DELETE CASCADE,
document_id BLOB NOT NULL REFERENCES document(id),
relpath TEXT NOT NULL CHECK (
length(relpath) > 0
AND substr(relpath, 1, 1) <> '/'
AND instr('/' || relpath || '/', '/../') = 0
AND instr('/' || relpath || '/', '/./') = 0
),
blob_root BLOB NOT NULL CHECK (length(blob_root) > 0),
state TEXT NOT NULL CHECK (state IN ('ok','pending','stale','error')),
updated_at INTEGER NOT NULL,
PRIMARY KEY (target_id, document_id),
UNIQUE (target_id, relpath)
) STRICT;
CREATE INDEX export_link_document ON export_link(document_id);
-- +goose Down
PRAGMA defer_foreign_keys = ON;
DROP TABLE IF EXISTS export_link;
DROP TABLE IF EXISTS export_target;
DROP TABLE IF EXISTS library_config;
DROP TABLE IF EXISTS acl_entry;
DROP TABLE IF EXISTS document;
DROP TABLE IF EXISTS document_version;
DROP TABLE IF EXISTS staging_item;
DROP TABLE IF EXISTS blob_location;
DROP TABLE IF EXISTS blob;
DROP TABLE IF EXISTS storage_backend;
DROP TABLE IF EXISTS storage_policy;
DROP TABLE IF EXISTS session;
DROP TABLE IF EXISTS account;
DROP TABLE IF EXISTS membership;
DROP TABLE IF EXISTS principal;
DROP TABLE IF EXISTS document_kind;
-36
View File
@@ -1,36 +0,0 @@
-- +goose Up
SELECT 'up SQL query';
CREATE TABLE principal (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL CHECK ( kind IN ('cluster','user','guest','group','system') ),
name TEXT NOT NULL CHECK ( length(name) > 0 ),
public_key BLOB,
status TEXT NOT NULL CHECK ( status IN ('active','disabled','revoked') ),
created_at INTEGER NOT NULL,
disabled_at INTEGER
);
CREATE TABLE membership (
group_id TEXT NOT NULL REFERENCES principal(id),
member_id TEXT NOT NULL REFERENCES principal(id),
role TEXT NOT NULL DEFAULT 'member' CHECK ( role IN ('member','admin') ),
created_at INTEGER NOT NULL,
disabled_at INTEGER,
PRIMARY KEY (group_id, member_id)
);
CREATE TABLE account (
principal_id TEXT PRIMARY KEY REFERENCES principal(id) ON DELETE CASCADE,
password_hash TEXT,
password_changed_at INTEGER,
must_change_password INTEGER NOT NULL DEFAULT 0 CHECK ( must_change_password IN (0,1) ),
state TEXT NOT NULL DEFAULT 'active' CHECK ( state IN ('active','locked','disabled') ),
failed_attempts INTEGER NOT NULL DEFAULT 0 CHECK ( failed_attempts >= 0 ),
locked_until INTEGER,
last_login_at INTEGER,
created_at INTEGER NOT NULL
);
-- +goose Down
SELECT 'down SQL query';
+118
View File
@@ -0,0 +1,118 @@
-- +goose Up
-- Groupes plats : un groupe contient des utilisateurs ou des invités, jamais d'autres groupes.
-- +goose StatementBegin
CREATE TRIGGER membership_check_ins BEFORE INSERT ON membership
WHEN COALESCE((SELECT kind FROM principal WHERE id = NEW.group_id), '') <> 'group'
OR COALESCE((SELECT kind FROM principal WHERE id = NEW.member_id), '') NOT IN ('user','guest')
BEGIN
SELECT RAISE(ABORT, 'membership : groupe plat, membres de type user ou guest uniquement');
END;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE TRIGGER membership_check_upd BEFORE UPDATE OF group_id, member_id ON membership
WHEN COALESCE((SELECT kind FROM principal WHERE id = NEW.group_id), '') <> 'group'
OR COALESCE((SELECT kind FROM principal WHERE id = NEW.member_id), '') NOT IN ('user','guest')
BEGIN
SELECT RAISE(ABORT, 'membership : groupe plat, membres de type user ou guest uniquement');
END;
-- +goose StatementEnd
-- Le chemin d'un nouveau nœud doit être celui de son parent + son identifiant,
-- et sa profondeur doit être celle du parent + 1.
-- +goose StatementBegin
CREATE TRIGGER document_path_ins BEFORE INSERT ON document
WHEN NEW.parent_id IS NOT NULL
AND (
NEW.path <> (SELECT path FROM document WHERE id = NEW.parent_id) || lower(hex(NEW.id)) || '/'
OR NEW.depth <> (SELECT depth + 1 FROM document WHERE id = NEW.parent_id)
)
BEGIN
SELECT RAISE(ABORT, 'document : path ou profondeur incohérents avec le parent');
END;
-- +goose StatementEnd
-- Les déplacements doivent mettre à jour path/depth de tout le sous-arbre.
-- Le cycle est refusé si le nouveau parent se trouve déjà dans le sous-arbre.
-- +goose StatementBegin
CREATE TRIGGER document_path_upd BEFORE UPDATE OF parent_id, path, depth ON document
WHEN NEW.parent_id IS NOT NULL
AND (
NEW.path <> (SELECT path FROM document WHERE id = NEW.parent_id) || lower(hex(NEW.id)) || '/'
OR NEW.depth <> (SELECT depth + 1 FROM document WHERE id = NEW.parent_id)
OR (SELECT path FROM document WHERE id = NEW.parent_id) LIKE OLD.path || '%'
)
BEGIN
SELECT RAISE(ABORT, 'document : déplacement invalide (path, profondeur ou cycle)');
END;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE TRIGGER document_root_upd BEFORE UPDATE OF parent_id, path, depth, kind ON document
WHEN NEW.parent_id IS NULL
AND (NEW.depth <> 0 OR NEW.path <> lower(hex(NEW.id)) || '/' OR NEW.kind <> 'library')
BEGIN
SELECT RAISE(ABORT, 'document : une racine doit être une bibliothèque (depth 0, path propre)');
END;
-- +goose StatementEnd
-- head_version_id doit désigner une version du même document.
-- +goose StatementBegin
CREATE TRIGGER document_head_version_ins BEFORE INSERT ON document
WHEN NEW.head_version_id IS NOT NULL
AND (SELECT document_id FROM document_version WHERE id = NEW.head_version_id) IS NOT NULL
AND (SELECT document_id FROM document_version WHERE id = NEW.head_version_id) <> NEW.id
BEGIN
SELECT RAISE(ABORT, 'document : head_version_id doit appartenir au document');
END;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE TRIGGER document_head_version_upd BEFORE UPDATE OF head_version_id ON document
WHEN NEW.head_version_id IS NOT NULL
AND (SELECT document_id FROM document_version WHERE id = NEW.head_version_id) IS NOT NULL
AND (SELECT document_id FROM document_version WHERE id = NEW.head_version_id) <> NEW.id
BEGIN
SELECT RAISE(ABORT, 'document : head_version_id doit appartenir au document');
END;
-- +goose StatementEnd
-- Jellyfin ignore les ACL : on n'exporte qu'une bibliothèque racine du cluster,
-- non PRIVATE, ou avec le consentement tracé de son propriétaire.
-- +goose StatementBegin
CREATE TRIGGER export_target_check_ins BEFORE INSERT ON export_target
WHEN COALESCE((SELECT kind FROM document WHERE id = NEW.library_id), '') <> 'library'
OR (SELECT parent_id FROM document WHERE id = NEW.library_id) IS NOT NULL
OR ( COALESCE((SELECT p.kind FROM document d JOIN principal p ON p.id = d.owner_id
WHERE d.id = NEW.library_id), '') <> 'cluster'
AND NEW.consent_by IS NULL )
OR COALESCE((SELECT visibility FROM document WHERE id = NEW.library_id), 'PRIVATE') = 'PRIVATE'
BEGIN
SELECT RAISE(ABORT, 'export_target : bibliothèque racine du cluster non PRIVATE, ou consentement du propriétaire requis');
END;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE TRIGGER export_target_check_upd BEFORE UPDATE OF library_id, consent_by ON export_target
WHEN COALESCE((SELECT kind FROM document WHERE id = NEW.library_id), '') <> 'library'
OR (SELECT parent_id FROM document WHERE id = NEW.library_id) IS NOT NULL
OR ( COALESCE((SELECT p.kind FROM document d JOIN principal p ON p.id = d.owner_id
WHERE d.id = NEW.library_id), '') <> 'cluster'
AND NEW.consent_by IS NULL )
OR COALESCE((SELECT visibility FROM document WHERE id = NEW.library_id), 'PRIVATE') = 'PRIVATE'
BEGIN
SELECT RAISE(ABORT, 'export_target : bibliothèque racine du cluster non PRIVATE, ou consentement du propriétaire requis');
END;
-- +goose StatementEnd
-- +goose Down
DROP TRIGGER IF EXISTS export_target_check_upd;
DROP TRIGGER IF EXISTS export_target_check_ins;
DROP TRIGGER IF EXISTS document_head_version_upd;
DROP TRIGGER IF EXISTS document_head_version_ins;
DROP TRIGGER IF EXISTS document_root_upd;
DROP TRIGGER IF EXISTS document_path_upd;
DROP TRIGGER IF EXISTS document_path_ins;
DROP TRIGGER IF EXISTS membership_check_upd;
DROP TRIGGER IF EXISTS membership_check_ins;
-5
View File
@@ -1,5 +0,0 @@
-- +goose Up
SELECT 'up SQL query';
-- +goose Down
SELECT 'down SQL query';
+44
View File
@@ -0,0 +1,44 @@
-- +goose Up
-- Politique et visibilité effectives, calculées de haut en bas.
CREATE VIEW v_document_effective AS
WITH RECURSIVE t(id, eff_visibility, eff_policy_id) AS (
SELECT id, visibility, policy_id FROM document
WHERE parent_id IS NULL AND deleted_at IS NULL
UNION ALL
SELECT d.id, COALESCE(d.visibility, t.eff_visibility), COALESCE(d.policy_id, t.eff_policy_id)
FROM document d JOIN t ON d.parent_id = t.id
WHERE d.deleted_at IS NULL
)
SELECT id, eff_visibility, eff_policy_id FROM t;
-- Blobs encore référencés par une version non purgée ou par un lien d'export.
CREATE VIEW v_blob_refs AS
SELECT root, SUM(refs) AS refs
FROM (
SELECT content_root AS root, COUNT(*) AS refs
FROM document_version
WHERE content_purged_at IS NULL
GROUP BY content_root
UNION ALL
SELECT blob_root AS root, COUNT(*) AS refs
FROM export_link
WHERE state <> 'stale'
GROUP BY blob_root
)
GROUP BY root;
-- Ce que l'administrateur peut voir des bibliothèques des autres : un volume, jamais des noms.
CREATE VIEW v_usage_by_owner AS
SELECT d.owner_id,
COUNT(*) AS documents,
COALESCE(SUM(v.size), 0) AS bytes
FROM document d
LEFT JOIN document_version v ON v.id = d.head_version_id
WHERE d.deleted_at IS NULL
GROUP BY d.owner_id;
-- +goose Down
DROP VIEW IF EXISTS v_usage_by_owner;
DROP VIEW IF EXISTS v_blob_refs;
DROP VIEW IF EXISTS v_document_effective;
+48
View File
@@ -0,0 +1,48 @@
-- +goose Up
-- Identifiants fixes et connus pour les comptes système (pas des UUIDv7, volontairement).
-- Le principal de type 'cluster' est créé à l'installation, avec la clé racine générée.
INSERT INTO principal (id, kind, name, created_at) VALUES
(x'00000000000070008000000000000001', 'system', 'system', CAST(strftime('%s','now') AS INTEGER) * 1000),
(x'00000000000070008000000000000002', 'group', 'admins', CAST(strftime('%s','now') AS INTEGER) * 1000),
(x'00000000000070008000000000000003', 'group', 'members', CAST(strftime('%s','now') AS INTEGER) * 1000),
(x'00000000000070008000000000000004', 'group', 'guests', CAST(strftime('%s','now') AS INTEGER) * 1000);
INSERT INTO document_kind (kind, provider, has_content, hidden) VALUES
('library', 'core', 0, 0),
('folder', 'core', 0, 0),
('movie', 'core', 0, 0),
('series', 'core', 0, 0),
('season', 'core', 0, 0),
('video', 'core', 1, 0),
('subtitle', 'core', 1, 0),
('image', 'core', 1, 0),
('file', 'core', 1, 0),
('computed/media-probe','core', 1, 1);
INSERT INTO storage_policy (id, name, mode, min_remote_replicas, created_at) VALUES
(x'00000000000070008000000000000101', 'cloud', 'cloud', 0, CAST(strftime('%s','now') AS INTEGER) * 1000),
(x'00000000000070008000000000000102', 'sync', 'sync', 0, CAST(strftime('%s','now') AS INTEGER) * 1000);
-- +goose Down
PRAGMA defer_foreign_keys = ON;
DELETE FROM storage_policy
WHERE id IN (
x'00000000000070008000000000000101',
x'00000000000070008000000000000102'
);
DELETE FROM document_kind
WHERE kind IN (
'library', 'folder', 'movie', 'series', 'season',
'video', 'subtitle', 'image', 'file', 'computed/media-probe'
);
DELETE FROM principal
WHERE id IN (
x'00000000000070008000000000000001',
x'00000000000070008000000000000002',
x'00000000000070008000000000000003',
x'00000000000070008000000000000004'
);
+180 -13
View File
@@ -6,10 +6,14 @@ package database
import (
"database/sql"
"mediarr/ident"
)
type Account struct {
PrincipalID string
PrincipalID ident.UUID
Login string
LoginKey string
PasswordHash sql.NullString
PasswordChangedAt sql.NullInt64
MustChangePassword int64
@@ -20,20 +24,183 @@ type Account struct {
CreatedAt int64
}
type AclEntry struct {
ID ident.UUID
DocumentID ident.UUID
SubjectID ident.UUID
Permissions int64
Propagate int64
ExpiresAt sql.NullInt64
GrantedBy ident.UUID
CreatedAt int64
RevokedAt sql.NullInt64
}
type Blob struct {
Root []byte
Size int64
State string
Role string
UnitSize int64
Have []byte
TreeState string
Encryption string
LastVerifiedAt sql.NullInt64
VerifyError sql.NullString
LastAccessAt sql.NullInt64
CreatedAt int64
}
type BlobLocation struct {
Root []byte
BackendID ident.UUID
Locator string
State string
CreatedAt int64
}
type Document struct {
ID ident.UUID
Kind string
OwnerID ident.UUID
CreatedBy ident.UUID
ParentID *ident.UUID
Name string
NameKey string
Path string
Depth int64
Position sql.NullString
HeadVersionID *ident.UUID
Metadata string
PolicyID *ident.UUID
Visibility sql.NullString
AclInherit int64
Rev int64
CreatedAt int64
UpdatedAt int64
DeletedAt sql.NullInt64
DeletedBy *ident.UUID
TrashBatch []byte
}
type DocumentKind struct {
Kind string
Provider string
HasContent int64
Hidden int64
MetadataSchema sql.NullString
}
type DocumentVersion struct {
ID ident.UUID
DocumentID ident.UUID
Seq int64
ContentRoot []byte
Size int64
Mime sql.NullString
AuthorID ident.UUID
DeviceID *ident.UUID
Origin string
Message sql.NullString
Pinned int64
ContentPurgedAt sql.NullInt64
CreatedAt int64
}
type ExportLink struct {
TargetID ident.UUID
DocumentID ident.UUID
Relpath string
BlobRoot []byte
State string
UpdatedAt int64
}
type ExportTarget struct {
ID ident.UUID
LibraryID ident.UUID
RootPath string
Mode string
Enabled int64
CheckState string
LastCheckAt sql.NullInt64
LastError sql.NullString
ConsentBy *ident.UUID
}
type LibraryConfig struct {
DocumentID ident.UUID
Protection string
AdminVisible int64
CreatedAt int64
}
type Membership struct {
GroupID string
MemberID string
Role string
CreatedAt int64
DisabledAt sql.NullInt64
GroupID ident.UUID
MemberID ident.UUID
Role string
CreatedAt int64
}
type Principal struct {
ID string
Kind string
Name string
PublicKey []byte
Status string
CreatedAt int64
DisabledAt sql.NullInt64
ID ident.UUID
Kind string
Name string
PublicKey []byte
Status string
SuccessorID *ident.UUID
CreatedAt int64
DisabledAt sql.NullInt64
}
type Session struct {
ID ident.UUID
TokenHash []byte
PrincipalID ident.UUID
Kind string
Label sql.NullString
UserAgent sql.NullString
IpPrefix sql.NullString
CreatedAt int64
LastSeenAt int64
ExpiresAt int64
IdleExpiresAt int64
RevokedAt sql.NullInt64
}
type StagingItem struct {
ID ident.UUID
Origin string
JobRef sql.NullString
Locator string
Size sql.NullInt64
State string
CreatedAt int64
UpdatedAt int64
}
type StorageBackend struct {
ID ident.UUID
Kind string
Name string
Config string
SecretRef sql.NullString
Enabled int64
CapacityBytes sql.NullInt64
State string
LastOkAt sql.NullInt64
LastError sql.NullString
CreatedAt int64
}
type StoragePolicy struct {
ID ident.UUID
Name string
Mode string
MinRemoteReplicas int64
ReplicateHistory int64
CacheTtlS sql.NullInt64
CacheMaxBytes sql.NullInt64
VersionRetention string
CreatedAt int64
}
+189 -129
View File
@@ -8,12 +8,16 @@ package database
import (
"context"
"database/sql"
"mediarr/ident"
)
const createAccount = `-- name: CreateAccount :one
INSERT INTO account (
principal_id,
login,
login_key,
password_hash,
password_changed_at,
must_change_password,
@@ -31,13 +35,17 @@ INSERT INTO account (
?6,
?7,
?8,
?9
?9,
?10,
?11
)
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
type CreateAccountParams struct {
PrincipalID string
PrincipalID ident.UUID
Login string
LoginKey string
PasswordHash sql.NullString
PasswordChangedAt sql.NullInt64
MustChangePassword int64
@@ -54,6 +62,8 @@ type CreateAccountParams struct {
func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (Account, error) {
row := q.db.QueryRowContext(ctx, createAccount,
arg.PrincipalID,
arg.Login,
arg.LoginKey,
arg.PasswordHash,
arg.PasswordChangedAt,
arg.MustChangePassword,
@@ -66,6 +76,8 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -84,24 +96,21 @@ INSERT INTO membership (
group_id,
member_id,
role,
created_at,
disabled_at
created_at
) VALUES (
?1,
?2,
?3,
?4,
?5
?4
)
RETURNING group_id, member_id, role, created_at, disabled_at
RETURNING group_id, member_id, role, created_at
`
type CreateMembershipParams struct {
GroupID string
MemberID string
Role string
CreatedAt int64
DisabledAt sql.NullInt64
GroupID ident.UUID
MemberID ident.UUID
Role string
CreatedAt int64
}
// ============================================================================
@@ -113,7 +122,6 @@ func (q *Queries) CreateMembership(ctx context.Context, arg CreateMembershipPara
arg.MemberID,
arg.Role,
arg.CreatedAt,
arg.DisabledAt,
)
var i Membership
err := row.Scan(
@@ -121,7 +129,6 @@ func (q *Queries) CreateMembership(ctx context.Context, arg CreateMembershipPara
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
@@ -134,6 +141,7 @@ INSERT INTO principal (
name,
public_key,
status,
successor_id,
created_at,
disabled_at
) VALUES (
@@ -143,19 +151,21 @@ INSERT INTO principal (
?4,
?5,
?6,
?7
?7,
?8
)
RETURNING id, kind, name, public_key, status, created_at, disabled_at
RETURNING id, kind, name, public_key, status, successor_id, created_at, disabled_at
`
type CreatePrincipalParams struct {
ID string
Kind string
Name string
PublicKey []byte
Status string
CreatedAt int64
DisabledAt sql.NullInt64
ID ident.UUID
Kind string
Name string
PublicKey []byte
Status string
SuccessorID *ident.UUID
CreatedAt int64
DisabledAt sql.NullInt64
}
// ============================================================================
@@ -168,6 +178,7 @@ func (q *Queries) CreatePrincipal(ctx context.Context, arg CreatePrincipalParams
arg.Name,
arg.PublicKey,
arg.Status,
arg.SuccessorID,
arg.CreatedAt,
arg.DisabledAt,
)
@@ -178,6 +189,7 @@ func (q *Queries) CreatePrincipal(ctx context.Context, arg CreatePrincipalParams
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
@@ -189,7 +201,7 @@ DELETE FROM account
WHERE principal_id = ?1
`
func (q *Queries) DeleteAccount(ctx context.Context, principalID string) error {
func (q *Queries) DeleteAccount(ctx context.Context, principalID ident.UUID) error {
_, err := q.db.ExecContext(ctx, deleteAccount, principalID)
return err
}
@@ -201,8 +213,8 @@ WHERE group_id = ?1
`
type DeleteMembershipParams struct {
GroupID string
MemberID string
GroupID ident.UUID
MemberID ident.UUID
}
func (q *Queries) DeleteMembership(ctx context.Context, arg DeleteMembershipParams) error {
@@ -215,75 +227,49 @@ DELETE FROM principal
WHERE id = ?1
`
func (q *Queries) DeletePrincipal(ctx context.Context, id string) error {
func (q *Queries) DeletePrincipal(ctx context.Context, id ident.UUID) error {
_, err := q.db.ExecContext(ctx, deletePrincipal, id)
return err
}
const disableMembership = `-- name: DisableMembership :one
UPDATE membership
SET disabled_at = ?1
WHERE group_id = ?2
AND member_id = ?3
RETURNING group_id, member_id, role, created_at, disabled_at
`
type DisableMembershipParams struct {
DisabledAt sql.NullInt64
GroupID string
MemberID string
}
func (q *Queries) DisableMembership(ctx context.Context, arg DisableMembershipParams) (Membership, error) {
row := q.db.QueryRowContext(ctx, disableMembership, arg.DisabledAt, arg.GroupID, arg.MemberID)
var i Membership
err := row.Scan(
&i.GroupID,
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
const enableMembership = `-- name: EnableMembership :one
UPDATE membership
SET disabled_at = NULL
WHERE group_id = ?1
AND member_id = ?2
RETURNING group_id, member_id, role, created_at, disabled_at
`
type EnableMembershipParams struct {
GroupID string
MemberID string
}
func (q *Queries) EnableMembership(ctx context.Context, arg EnableMembershipParams) (Membership, error) {
row := q.db.QueryRowContext(ctx, enableMembership, arg.GroupID, arg.MemberID)
var i Membership
err := row.Scan(
&i.GroupID,
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
const getAccount = `-- name: GetAccount :one
SELECT principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
SELECT principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
FROM account
WHERE principal_id = ?1
`
func (q *Queries) GetAccount(ctx context.Context, principalID string) (Account, error) {
func (q *Queries) GetAccount(ctx context.Context, principalID ident.UUID) (Account, error) {
row := q.db.QueryRowContext(ctx, getAccount, principalID)
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
&i.State,
&i.FailedAttempts,
&i.LockedUntil,
&i.LastLoginAt,
&i.CreatedAt,
)
return i, err
}
const getAccountByLoginKey = `-- name: GetAccountByLoginKey :one
SELECT principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
FROM account
WHERE login_key = ?1
`
func (q *Queries) GetAccountByLoginKey(ctx context.Context, loginKey string) (Account, error) {
row := q.db.QueryRowContext(ctx, getAccountByLoginKey, loginKey)
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -297,15 +283,15 @@ func (q *Queries) GetAccount(ctx context.Context, principalID string) (Account,
}
const getMembership = `-- name: GetMembership :one
SELECT group_id, member_id, role, created_at, disabled_at
SELECT group_id, member_id, role, created_at
FROM membership
WHERE group_id = ?1
AND member_id = ?2
`
type GetMembershipParams struct {
GroupID string
MemberID string
GroupID ident.UUID
MemberID ident.UUID
}
func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
@@ -316,18 +302,17 @@ func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (M
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
const getPrincipal = `-- name: GetPrincipal :one
SELECT id, kind, name, public_key, status, created_at, disabled_at
SELECT id, kind, name, public_key, status, successor_id, created_at, disabled_at
FROM principal
WHERE id = ?1
`
func (q *Queries) GetPrincipal(ctx context.Context, id string) (Principal, error) {
func (q *Queries) GetPrincipal(ctx context.Context, id ident.UUID) (Principal, error) {
row := q.db.QueryRowContext(ctx, getPrincipal, id)
var i Principal
err := row.Scan(
@@ -336,6 +321,7 @@ func (q *Queries) GetPrincipal(ctx context.Context, id string) (Principal, error
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
@@ -343,7 +329,7 @@ func (q *Queries) GetPrincipal(ctx context.Context, id string) (Principal, error
}
const getPrincipalByName = `-- name: GetPrincipalByName :one
SELECT id, kind, name, public_key, status, created_at, disabled_at
SELECT id, kind, name, public_key, status, successor_id, created_at, disabled_at
FROM principal
WHERE name = ?1
`
@@ -357,6 +343,35 @@ func (q *Queries) GetPrincipalByName(ctx context.Context, name string) (Principa
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
const getPrincipalByNameAndKind = `-- name: GetPrincipalByNameAndKind :one
SELECT id, kind, name, public_key, status, successor_id, created_at, disabled_at
FROM principal
WHERE kind = ?1
AND name = ?2
`
type GetPrincipalByNameAndKindParams struct {
Kind string
Name string
}
func (q *Queries) GetPrincipalByNameAndKind(ctx context.Context, arg GetPrincipalByNameAndKindParams) (Principal, error) {
row := q.db.QueryRowContext(ctx, getPrincipalByNameAndKind, arg.Kind, arg.Name)
var i Principal
err := row.Scan(
&i.ID,
&i.Kind,
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
@@ -367,14 +382,16 @@ const incrementFailedAttempts = `-- name: IncrementFailedAttempts :one
UPDATE account
SET failed_attempts = failed_attempts + 1
WHERE principal_id = ?1
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
func (q *Queries) IncrementFailedAttempts(ctx context.Context, principalID string) (Account, error) {
func (q *Queries) IncrementFailedAttempts(ctx context.Context, principalID ident.UUID) (Account, error) {
row := q.db.QueryRowContext(ctx, incrementFailedAttempts, principalID)
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -388,7 +405,7 @@ func (q *Queries) IncrementFailedAttempts(ctx context.Context, principalID strin
}
const listActivePrincipals = `-- name: ListActivePrincipals :many
SELECT id, kind, name, public_key, status, created_at, disabled_at
SELECT id, kind, name, public_key, status, successor_id, created_at, disabled_at
FROM principal
WHERE status = 'active'
ORDER BY name
@@ -409,6 +426,7 @@ func (q *Queries) ListActivePrincipals(ctx context.Context) ([]Principal, error)
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
@@ -426,15 +444,14 @@ func (q *Queries) ListActivePrincipals(ctx context.Context) ([]Principal, error)
}
const listGroupMembers = `-- name: ListGroupMembers :many
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.created_at, p.disabled_at
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
FROM membership m
JOIN principal p ON p.id = m.member_id
WHERE m.group_id = ?1
AND m.disabled_at IS NULL
ORDER BY p.name
`
func (q *Queries) ListGroupMembers(ctx context.Context, groupID string) ([]Principal, error) {
func (q *Queries) ListGroupMembers(ctx context.Context, groupID ident.UUID) ([]Principal, error) {
rows, err := q.db.QueryContext(ctx, listGroupMembers, groupID)
if err != nil {
return nil, err
@@ -449,6 +466,7 @@ func (q *Queries) ListGroupMembers(ctx context.Context, groupID string) ([]Princ
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
@@ -466,15 +484,14 @@ func (q *Queries) ListGroupMembers(ctx context.Context, groupID string) ([]Princ
}
const listMemberGroups = `-- name: ListMemberGroups :many
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.created_at, p.disabled_at
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
FROM membership m
JOIN principal p ON p.id = m.group_id
WHERE m.member_id = ?1
AND m.disabled_at IS NULL
ORDER BY p.name
`
func (q *Queries) ListMemberGroups(ctx context.Context, memberID string) ([]Principal, error) {
func (q *Queries) ListMemberGroups(ctx context.Context, memberID ident.UUID) ([]Principal, error) {
rows, err := q.db.QueryContext(ctx, listMemberGroups, memberID)
if err != nil {
return nil, err
@@ -489,6 +506,7 @@ func (q *Queries) ListMemberGroups(ctx context.Context, memberID string) ([]Prin
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
@@ -506,13 +524,13 @@ func (q *Queries) ListMemberGroups(ctx context.Context, memberID string) ([]Prin
}
const listMembershipsByGroup = `-- name: ListMembershipsByGroup :many
SELECT group_id, member_id, role, created_at, disabled_at
SELECT group_id, member_id, role, created_at
FROM membership
WHERE group_id = ?1
ORDER BY created_at
`
func (q *Queries) ListMembershipsByGroup(ctx context.Context, groupID string) ([]Membership, error) {
func (q *Queries) ListMembershipsByGroup(ctx context.Context, groupID ident.UUID) ([]Membership, error) {
rows, err := q.db.QueryContext(ctx, listMembershipsByGroup, groupID)
if err != nil {
return nil, err
@@ -526,7 +544,6 @@ func (q *Queries) ListMembershipsByGroup(ctx context.Context, groupID string) ([
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
return nil, err
}
@@ -542,13 +559,13 @@ func (q *Queries) ListMembershipsByGroup(ctx context.Context, groupID string) ([
}
const listMembershipsByMember = `-- name: ListMembershipsByMember :many
SELECT group_id, member_id, role, created_at, disabled_at
SELECT group_id, member_id, role, created_at
FROM membership
WHERE member_id = ?1
ORDER BY created_at
`
func (q *Queries) ListMembershipsByMember(ctx context.Context, memberID string) ([]Membership, error) {
func (q *Queries) ListMembershipsByMember(ctx context.Context, memberID ident.UUID) ([]Membership, error) {
rows, err := q.db.QueryContext(ctx, listMembershipsByMember, memberID)
if err != nil {
return nil, err
@@ -562,7 +579,6 @@ func (q *Queries) ListMembershipsByMember(ctx context.Context, memberID string)
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
return nil, err
}
@@ -578,7 +594,7 @@ func (q *Queries) ListMembershipsByMember(ctx context.Context, memberID string)
}
const listPrincipals = `-- name: ListPrincipals :many
SELECT id, kind, name, public_key, status, created_at, disabled_at
SELECT id, kind, name, public_key, status, successor_id, created_at, disabled_at
FROM principal
ORDER BY name
`
@@ -598,6 +614,7 @@ func (q *Queries) ListPrincipals(ctx context.Context) ([]Principal, error) {
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
@@ -615,7 +632,7 @@ func (q *Queries) ListPrincipals(ctx context.Context) ([]Principal, error) {
}
const listPrincipalsByKind = `-- name: ListPrincipalsByKind :many
SELECT id, kind, name, public_key, status, created_at, disabled_at
SELECT id, kind, name, public_key, status, successor_id, created_at, disabled_at
FROM principal
WHERE kind = ?1
ORDER BY name
@@ -636,6 +653,7 @@ func (q *Queries) ListPrincipalsByKind(ctx context.Context, kind string) ([]Prin
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
); err != nil {
@@ -657,12 +675,12 @@ UPDATE account
SET state = 'locked',
locked_until = ?1
WHERE principal_id = ?2
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
type LockAccountParams struct {
LockedUntil sql.NullInt64
PrincipalID string
PrincipalID ident.UUID
}
func (q *Queries) LockAccount(ctx context.Context, arg LockAccountParams) (Account, error) {
@@ -670,6 +688,8 @@ func (q *Queries) LockAccount(ctx context.Context, arg LockAccountParams) (Accou
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -688,12 +708,12 @@ SET last_login_at = ?1,
failed_attempts = 0,
locked_until = NULL
WHERE principal_id = ?2
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
type RecordLoginParams struct {
LastLoginAt sql.NullInt64
PrincipalID string
PrincipalID ident.UUID
}
func (q *Queries) RecordLogin(ctx context.Context, arg RecordLoginParams) (Account, error) {
@@ -701,6 +721,8 @@ func (q *Queries) RecordLogin(ctx context.Context, arg RecordLoginParams) (Accou
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -718,14 +740,16 @@ UPDATE account
SET failed_attempts = 0,
locked_until = NULL
WHERE principal_id = ?1
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
func (q *Queries) ResetFailedAttempts(ctx context.Context, principalID string) (Account, error) {
func (q *Queries) ResetFailedAttempts(ctx context.Context, principalID ident.UUID) (Account, error) {
row := q.db.QueryRowContext(ctx, resetFailedAttempts, principalID)
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -744,14 +768,16 @@ SET state = 'active',
failed_attempts = 0,
locked_until = NULL
WHERE principal_id = ?1
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
func (q *Queries) UnlockAccount(ctx context.Context, principalID string) (Account, error) {
func (q *Queries) UnlockAccount(ctx context.Context, principalID ident.UUID) (Account, error) {
row := q.db.QueryRowContext(ctx, unlockAccount, principalID)
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -768,12 +794,12 @@ const updateAccountState = `-- name: UpdateAccountState :one
UPDATE account
SET state = ?1
WHERE principal_id = ?2
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
type UpdateAccountStateParams struct {
State string
PrincipalID string
PrincipalID ident.UUID
}
func (q *Queries) UpdateAccountState(ctx context.Context, arg UpdateAccountStateParams) (Account, error) {
@@ -781,6 +807,8 @@ func (q *Queries) UpdateAccountState(ctx context.Context, arg UpdateAccountState
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -798,13 +826,13 @@ UPDATE membership
SET role = ?1
WHERE group_id = ?2
AND member_id = ?3
RETURNING group_id, member_id, role, created_at, disabled_at
RETURNING group_id, member_id, role, created_at
`
type UpdateMembershipRoleParams struct {
Role string
GroupID string
MemberID string
GroupID ident.UUID
MemberID ident.UUID
}
func (q *Queries) UpdateMembershipRole(ctx context.Context, arg UpdateMembershipRoleParams) (Membership, error) {
@@ -815,7 +843,6 @@ func (q *Queries) UpdateMembershipRole(ctx context.Context, arg UpdateMembership
&i.MemberID,
&i.Role,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
@@ -828,13 +855,13 @@ SET password_hash = ?1,
failed_attempts = 0,
locked_until = NULL
WHERE principal_id = ?3
RETURNING principal_id, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
`
type UpdatePasswordParams struct {
PasswordHash sql.NullString
PasswordChangedAt sql.NullInt64
PrincipalID string
PrincipalID ident.UUID
}
func (q *Queries) UpdatePassword(ctx context.Context, arg UpdatePasswordParams) (Account, error) {
@@ -842,6 +869,8 @@ func (q *Queries) UpdatePassword(ctx context.Context, arg UpdatePasswordParams)
var i Account
err := row.Scan(
&i.PrincipalID,
&i.Login,
&i.LoginKey,
&i.PasswordHash,
&i.PasswordChangedAt,
&i.MustChangePassword,
@@ -858,12 +887,12 @@ const updatePrincipalName = `-- name: UpdatePrincipalName :one
UPDATE principal
SET name = ?1
WHERE id = ?2
RETURNING id, kind, name, public_key, status, created_at, disabled_at
RETURNING id, kind, name, public_key, status, successor_id, created_at, disabled_at
`
type UpdatePrincipalNameParams struct {
Name string
ID string
ID ident.UUID
}
func (q *Queries) UpdatePrincipalName(ctx context.Context, arg UpdatePrincipalNameParams) (Principal, error) {
@@ -875,6 +904,7 @@ func (q *Queries) UpdatePrincipalName(ctx context.Context, arg UpdatePrincipalNa
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
@@ -885,12 +915,12 @@ const updatePrincipalPublicKey = `-- name: UpdatePrincipalPublicKey :one
UPDATE principal
SET public_key = ?1
WHERE id = ?2
RETURNING id, kind, name, public_key, status, created_at, disabled_at
RETURNING id, kind, name, public_key, status, successor_id, created_at, disabled_at
`
type UpdatePrincipalPublicKeyParams struct {
PublicKey []byte
ID string
ID ident.UUID
}
func (q *Queries) UpdatePrincipalPublicKey(ctx context.Context, arg UpdatePrincipalPublicKeyParams) (Principal, error) {
@@ -902,6 +932,7 @@ func (q *Queries) UpdatePrincipalPublicKey(ctx context.Context, arg UpdatePrinci
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
@@ -913,13 +944,13 @@ UPDATE principal
SET status = ?1,
disabled_at = ?2
WHERE id = ?3
RETURNING id, kind, name, public_key, status, created_at, disabled_at
RETURNING id, kind, name, public_key, status, successor_id, created_at, disabled_at
`
type UpdatePrincipalStatusParams struct {
Status string
DisabledAt sql.NullInt64
ID string
ID ident.UUID
}
func (q *Queries) UpdatePrincipalStatus(ctx context.Context, arg UpdatePrincipalStatusParams) (Principal, error) {
@@ -931,6 +962,35 @@ func (q *Queries) UpdatePrincipalStatus(ctx context.Context, arg UpdatePrincipal
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
return i, err
}
const updatePrincipalSuccessor = `-- name: UpdatePrincipalSuccessor :one
UPDATE principal
SET successor_id = ?1
WHERE id = ?2
RETURNING id, kind, name, public_key, status, successor_id, created_at, disabled_at
`
type UpdatePrincipalSuccessorParams struct {
SuccessorID *ident.UUID
ID ident.UUID
}
func (q *Queries) UpdatePrincipalSuccessor(ctx context.Context, arg UpdatePrincipalSuccessorParams) (Principal, error) {
row := q.db.QueryRowContext(ctx, updatePrincipalSuccessor, arg.SuccessorID, arg.ID)
var i Principal
err := row.Scan(
&i.ID,
&i.Kind,
&i.Name,
&i.PublicKey,
&i.Status,
&i.SuccessorID,
&i.CreatedAt,
&i.DisabledAt,
)
+25 -20
View File
@@ -9,6 +9,7 @@ INSERT INTO principal (
name,
public_key,
status,
successor_id,
created_at,
disabled_at
) VALUES (
@@ -17,6 +18,7 @@ INSERT INTO principal (
sqlc.arg(name),
sqlc.narg(public_key),
sqlc.arg(status),
sqlc.narg(successor_id),
sqlc.arg(created_at),
sqlc.narg(disabled_at)
)
@@ -32,6 +34,12 @@ SELECT *
FROM principal
WHERE name = sqlc.arg(name);
-- name: GetPrincipalByNameAndKind :one
SELECT *
FROM principal
WHERE kind = sqlc.arg(kind)
AND name = sqlc.arg(name);
-- name: ListPrincipals :many
SELECT *
FROM principal
@@ -68,6 +76,12 @@ SET status = sqlc.arg(status),
WHERE id = sqlc.arg(id)
RETURNING *;
-- name: UpdatePrincipalSuccessor :one
UPDATE principal
SET successor_id = sqlc.narg(successor_id)
WHERE id = sqlc.arg(id)
RETURNING *;
-- name: DeletePrincipal :exec
DELETE FROM principal
WHERE id = sqlc.arg(id);
@@ -81,14 +95,12 @@ INSERT INTO membership (
group_id,
member_id,
role,
created_at,
disabled_at
created_at
) VALUES (
sqlc.arg(group_id),
sqlc.arg(member_id),
sqlc.arg(role),
sqlc.arg(created_at),
sqlc.narg(disabled_at)
sqlc.arg(created_at)
)
RETURNING *;
@@ -115,7 +127,6 @@ SELECT p.*
FROM membership m
JOIN principal p ON p.id = m.member_id
WHERE m.group_id = sqlc.arg(group_id)
AND m.disabled_at IS NULL
ORDER BY p.name;
-- name: ListMemberGroups :many
@@ -123,7 +134,6 @@ SELECT p.*
FROM membership m
JOIN principal p ON p.id = m.group_id
WHERE m.member_id = sqlc.arg(member_id)
AND m.disabled_at IS NULL
ORDER BY p.name;
-- name: UpdateMembershipRole :one
@@ -133,20 +143,6 @@ WHERE group_id = sqlc.arg(group_id)
AND member_id = sqlc.arg(member_id)
RETURNING *;
-- name: DisableMembership :one
UPDATE membership
SET disabled_at = sqlc.arg(disabled_at)
WHERE group_id = sqlc.arg(group_id)
AND member_id = sqlc.arg(member_id)
RETURNING *;
-- name: EnableMembership :one
UPDATE membership
SET disabled_at = NULL
WHERE group_id = sqlc.arg(group_id)
AND member_id = sqlc.arg(member_id)
RETURNING *;
-- name: DeleteMembership :exec
DELETE FROM membership
WHERE group_id = sqlc.arg(group_id)
@@ -159,6 +155,8 @@ WHERE group_id = sqlc.arg(group_id)
-- name: CreateAccount :one
INSERT INTO account (
principal_id,
login,
login_key,
password_hash,
password_changed_at,
must_change_password,
@@ -169,6 +167,8 @@ INSERT INTO account (
created_at
) VALUES (
sqlc.arg(principal_id),
sqlc.arg(login),
sqlc.arg(login_key),
sqlc.narg(password_hash),
sqlc.narg(password_changed_at),
sqlc.arg(must_change_password),
@@ -185,6 +185,11 @@ SELECT *
FROM account
WHERE principal_id = sqlc.arg(principal_id);
-- name: GetAccountByLoginKey :one
SELECT *
FROM account
WHERE login_key = sqlc.arg(login_key);
-- name: UpdatePassword :one
UPDATE account
SET password_hash = sqlc.arg(password_hash),