Files
Febe/src/Febe.Data/Migrations/0003_esportazione.sql
T
Alby96andClaude Opus 5.5 980212fb50
verifica / controlli (push) Successful in 28s
verifica / prove (push) Successful in 26m53s
verifica / installatore (push) Successful in 2m13s
verifica / immagine (push) Successful in 20m12s
E1: le copie della cartella generale tornano con l'account, un rifiuto per ogni CHECK (#58)
La seconda revisione ha trovato che le copie della cartella generale di un account
rimosso e aggiunto di nuovo restavano orfane per sempre: una «Tolto» o «Superato»
senza file da adottare si sarebbe ricopiata da sola, contro §4.10.

- export_copy tiene identificativo Instagram e nome dell'account rimosso, solo sulle
  copie orfane (CHECK, ix_export_copy_orphan); AccountStore.DeleteAsync li scrive.
- RelinkOrphanCopiesAsync ridà all'account le sue copie della cartella generale, per
  identificativo o, se la copia non lo ha, per nome; AddAsync, UpdateAsync e
  RenameAsync lo chiamano nella loro transazione. La cartella propria resta ad
  AttachDestinationAsync.
- Ogni CHECK della 0003 ha una prova di rifiuto su una riga valida per tutti gli
  altri; ambito, variante e formato sconosciuti si controllano anche sullo schema.
- SPECIFICA §4.10 e §8.3, decisioni.md e stato.md aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:32:40 +01:00

262 lines
21 KiB
SQL

-- Febe, schema version 3: export (tappa E1 of 0.3.0, issue #58; spec §4.10, §8.3).
-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner.
-- Only new tables and indexes: no column or index of the existing tables changes. The only existing paths that touch
-- the new tables are in AccountStore: DeleteAsync disables the account's destinations and keeps its user name on them,
-- and keeps its Instagram id and user name on its copies, before deleting the account; AddAsync, UpdateAsync and
-- RenameAsync give the account back its orphan copies of the general folder (nothing to do while there are no
-- destinations and no copies); nothing else reads or writes them yet (tappa E1: no behaviour change). Times are UTC Unix milliseconds; enumerations are their English names,
-- checked here. Paths in a destination are relative to its root, '/' separated, NFC; paths of converted library files
-- are relative to the account folder, like media.relative_path. Every foreign key has an index on its child column.
-- A destination (spec §4.10 «Destinazioni»): the general export folder (scope General) or the own folder of an account
-- (scope Account), which replaces the general one for that account. One row is one root folder for ever: choosing
-- another folder retires the row (removed_at) and adds a new one, so «già copiato» never points at a folder the copies
-- were not written to. Retired rows stay with their copies (spec §4.10: removing a destination removes only the
-- configuration; §13.2: export_copy is all Febe knows of the copies). Removing an account never deletes its row, it
-- disables it: AccountStore.DeleteAsync turns «Automatica» off (forgetting «Solo i nuovi») and keeps the user name in the
-- same transaction, then ON DELETE SET NULL clears the link, and the row stays inactive until the account is attached
-- again, still with «Automatica» off; the last two CHECKs make any path that forgets either fail.
CREATE TABLE export_destination (
id INTEGER PRIMARY KEY,
scope TEXT NOT NULL CHECK (scope IN ('General', 'Account')),
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
-- User name of the account when it was removed, so the destination can still be named («era di @nome»).
removed_account_username TEXT CHECK (removed_account_username IS NULL OR length(removed_account_username) > 0),
-- Name shown in the interface («Disco USB»); NULL: the last segment of root_path.
label TEXT CHECK (label IS NULL OR length(label) > 0),
-- Root folder as chosen (Windows: full path, UNC included; Docker: a subfolder of /esporta). Never created by Febe,
-- never changed (see above).
root_path TEXT NOT NULL CHECK (length(root_path) > 0),
-- ContentTypes flags (PostPhotos 1, PostVideos 2, Stories 4, Highlights 8, Tagged 16, ProfilePicture 32).
content_types INTEGER NOT NULL CHECK (content_types >= 0),
-- Formats of the copies, as requested; NULL: «Come le impostazioni generali» (esportazione.formato-foto/-video).
photo_format TEXT CHECK (photo_format IS NULL OR photo_format IN ('Original', 'Jpg', 'Png', 'WebpLossless')),
video_format TEXT CHECK (video_format IS NULL OR video_format IN ('Original', 'Mp4')),
-- The three naming schemes of §4.7 (general, highlight collections, profile pictures) under the destination, checked
-- like the library's; each NULL: «Come la libreria» (libreria.schema, libreria.schema-evidenza, libreria.schema-profilo).
naming_scheme TEXT CHECK (naming_scheme IS NULL OR length(naming_scheme) > 0),
highlight_naming_scheme TEXT CHECK (highlight_naming_scheme IS NULL OR length(highlight_naming_scheme) > 0),
profile_naming_scheme TEXT CHECK (profile_naming_scheme IS NULL OR length(profile_naming_scheme) > 0),
-- «Automatica» (off by default). automatic_since is the answer «Solo i nuovi»: files whose media.downloaded_at (the
-- time of their _febe.jsonl line, kept by a rebuild) is at or after it; NULL with automatic = 1: everything. Turning
-- the switch off forgets the answer, so the next activation asks again.
automatic INTEGER NOT NULL DEFAULT 0 CHECK (automatic IN (0, 1)),
automatic_since INTEGER,
-- The probe file could not be written: the destination is paused until a later check succeeds (spec §4.10).
paused_at INTEGER,
last_error TEXT,
created_at INTEGER NOT NULL,
-- Retired: removed by Alberto, or replaced by a row with another folder. Never automatic again.
removed_at INTEGER,
CHECK (automatic = 1 OR automatic_since IS NULL),
CHECK (removed_at IS NULL OR automatic = 0),
CHECK (scope = 'Account' OR (account_id IS NULL AND removed_account_username IS NULL)),
CHECK (scope = 'General' OR account_id IS NOT NULL OR removed_account_username IS NOT NULL),
-- An own folder without its account (orphan) is never automatic.
CHECK (scope = 'General' OR account_id IS NOT NULL OR automatic = 0)
);
-- At most one general folder in use.
CREATE UNIQUE INDEX ux_export_destination_general ON export_destination (scope) WHERE scope = 'General' AND removed_at IS NULL;
-- At most one own folder in use per account: with the general folder, at most one effective destination per account.
CREATE UNIQUE INDEX ux_export_destination_account ON export_destination (account_id) WHERE account_id IS NOT NULL AND removed_at IS NULL;
-- Foreign key of the account (SET NULL): the unique index above is partial on removed_at and cannot serve it.
CREATE INDEX ix_export_destination_account ON export_destination (account_id) WHERE account_id IS NOT NULL;
-- «Esporta questo account» (spec §4.10; scheda account → Impostazioni, «Copie esterne»): a switch of the account,
-- whatever its effective destination, not a destination. No row: the default, decided by tappa E2. A setting of the
-- account, so it goes with it (CASCADE); no column in account (spec §8.3).
CREATE TABLE export_account (
account_id INTEGER PRIMARY KEY REFERENCES account (id) ON DELETE CASCADE,
enabled INTEGER NOT NULL CHECK (enabled IN (0, 1))
);
-- A copy made (spec §4.10 «Già copiato»). Its identity is SHA-256 of the original, destination, effective account,
-- variant, format and frame instant, always the effective ones: a byte-for-byte result (same format as the source,
-- HEIC, animated images, a video that cannot be remuxed) is Whole/Original whatever was requested. Removed and
-- Superseded rows stay as history and are never copied again by themselves, only by «Copia di nuovo», which adds a new
-- row; so only the current row of an identity (Copied or Failed) is unique, and the latest row of an identity in any
-- state answers «may this be queued automatically?». The row outlives the library: deleting an entry or its files sets
-- media_id to NULL and keeps source_sha256, so an entry deleted with «Eliminalo e lascia che torni» finds its copies
-- again by SHA-256. A destination with copies cannot be deleted (RESTRICT): it is retired instead.
CREATE TABLE export_copy (
id INTEGER PRIMARY KEY,
destination_id INTEGER NOT NULL REFERENCES export_destination (id) ON DELETE RESTRICT,
-- Effective account: the account segment in the general folder, or the account of its own folder. NULL only after
-- the account was removed («orphan»): only AccountStore.DeleteAsync writes NULL, with the two columns below, in the
-- transaction that deletes the account (ON DELETE SET NULL then finds nothing left to clear).
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
-- Instagram id and user name of the account when it was removed, on orphan rows only, so the account added again
-- (a new account id) finds its copies again: those of the general folder come back by themselves, any state, when
-- the account is added or its id or name written (by Instagram id when both have one, else by user name, only for a
-- row without one); those of its own folder when the folder is attached to it again; any row when its file is
-- adopted again by path. Both NULL on an orphan whose account is unknown (a raw delete): it comes back only by
-- adoption. Without them a Removed or Superseded row of the general folder, which has no file to adopt, would be
-- lost to the account added again and its file copied again by itself (spec §4.10).
removed_account_instagram_id TEXT CHECK (removed_account_instagram_id IS NULL OR length(removed_account_instagram_id) > 0),
removed_account_username TEXT COLLATE NOCASE CHECK (removed_account_username IS NULL OR length(removed_account_username) > 0),
media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
source_sha256 TEXT NOT NULL CHECK (length(source_sha256) = 64),
variant TEXT NOT NULL CHECK (variant IN ('Whole', 'Converted', 'Frame')),
format TEXT NOT NULL CHECK (format IN ('Original', 'Jpg', 'Png', 'WebpLossless', 'Mp4')),
frame_at_ms INTEGER CHECK (frame_at_ms IS NULL OR frame_at_ms >= 0),
state TEXT NOT NULL CHECK (state IN ('Copied', 'Removed', 'Superseded', 'Failed')),
-- SHA-256 of the library file that took the place of the original («Tieni il più grande», a rebuild). Required for
-- Superseded, allowed on Removed, so the new file is not «Non ancora copiato» and is never queued by itself. Never
-- the original itself: when the library file goes back to it, the copy matches again (see SupersedeCopiesAsync).
superseded_by_sha256 TEXT CHECK (superseded_by_sha256 IS NULL OR length(superseded_by_sha256) = 64),
-- Written by Febe, or an existing file adopted by path (spec §4.10 «Adozione per percorso»).
origin TEXT NOT NULL DEFAULT 'Written' CHECK (origin IN ('Written', 'Adopted')),
-- NOCASE: destinations are Windows and SMB folders, where Mario/x.jpg and mario/X.jpg are one file (ASCII only).
relative_path TEXT COLLATE NOCASE CHECK (relative_path IS NULL OR length(relative_path) > 0),
bytes INTEGER CHECK (bytes IS NULL OR bytes >= 0),
copy_sha256 TEXT CHECK (copy_sha256 IS NULL OR length(copy_sha256) = 64),
copied_at INTEGER NOT NULL,
state_changed_at INTEGER,
last_error TEXT,
-- A whole copy is byte for byte; a conversion changes the format; a frame is a picture at an instant.
CHECK ((variant = 'Whole' AND format = 'Original')
OR (variant = 'Converted' AND format IN ('Jpg', 'Png', 'WebpLossless', 'Mp4'))
OR (variant = 'Frame' AND format IN ('Jpg', 'Png', 'WebpLossless'))),
CHECK ((variant = 'Frame') = (frame_at_ms IS NOT NULL)),
-- Every state but Failed had a file in the destination.
CHECK (state = 'Failed' OR (relative_path IS NOT NULL AND bytes IS NOT NULL AND copy_sha256 IS NOT NULL)),
-- Whole copies have the SHA-256 of their original, and only they: a converted file equal to its original is Whole.
CHECK (copy_sha256 IS NULL OR (variant = 'Whole') = (copy_sha256 = source_sha256)),
CHECK (state <> 'Superseded' OR superseded_by_sha256 IS NOT NULL),
CHECK (superseded_by_sha256 IS NULL OR state IN ('Superseded', 'Removed')),
CHECK (superseded_by_sha256 IS NULL OR superseded_by_sha256 <> source_sha256),
-- The removed account is remembered only while the row has no account: re-linking clears it.
CHECK (account_id IS NULL OR (removed_account_instagram_id IS NULL AND removed_account_username IS NULL))
);
-- The copy identity: one current row (Copied or Failed) per identity. NULL account_id (orphan) is distinct.
CREATE UNIQUE INDEX ux_export_copy_identity ON export_copy
(destination_id, source_sha256, account_id, variant, format, ifnull(frame_at_ms, -1))
WHERE state IN ('Copied', 'Failed');
-- Never two rows on one file: a path holding a Copied or Superseded copy is taken (a Removed one is free again).
CREATE UNIQUE INDEX ux_export_copy_path ON export_copy (destination_id, relative_path)
WHERE state IN ('Copied', 'Superseded');
-- Foreign key of the destination (RESTRICT), counts per state (Dashboard «Esportazione»), the walk of a destination
-- («Riconosci», Tolto checks), and the set shape of the «Copie» filter over the whole library (E2), from the index alone.
CREATE INDEX ix_export_copy_destination ON export_copy (destination_id, state, source_sha256, account_id);
-- The copies of a destination by key (ListCopiesAsync, with or without a state): (destination_id, rowid), so a page
-- reads on from the last key instead of sorting every copy of the destination again.
CREATE INDEX ix_export_copy_destination_id ON export_copy (destination_id);
-- Lookups by SHA-256 (spec §4.10: «Si cerca per SHA-256»): viewer File panel, «Una copia sola», entries that come back,
-- the EXISTS of the «Copie» filter inside a window, and the latest row of an identity in any state (rowid order).
CREATE INDEX ix_export_copy_sha256 ON export_copy
(source_sha256, destination_id, account_id, variant, format, ifnull(frame_at_ms, -1));
-- Superseded and Removed copies of a library file that changed, by the SHA-256 of the file now in the library.
CREATE INDEX ix_export_copy_superseded_by ON export_copy (superseded_by_sha256, destination_id, account_id)
WHERE superseded_by_sha256 IS NOT NULL;
-- Foreign keys with SET NULL.
CREATE INDEX ix_export_copy_media ON export_copy (media_id) WHERE media_id IS NOT NULL;
CREATE INDEX ix_export_copy_account ON export_copy (account_id) WHERE account_id IS NOT NULL;
-- The orphan copies of a removed account, by its Instagram id, or by its user name for rows without one (re-linking).
CREATE INDEX ix_export_copy_orphan ON export_copy (removed_account_instagram_id, removed_account_username)
WHERE account_id IS NULL;
-- An export job (on the model of import_run): «Copia in…», the automatic export, «Riconosci le copie già presenti».
-- Interrupted (Febe closed) and Paused (destination not reachable) runs resume from their pending items.
CREATE TABLE export_run (
id INTEGER PRIMARY KEY,
destination_id INTEGER NOT NULL REFERENCES export_destination (id) ON DELETE RESTRICT,
kind TEXT NOT NULL CHECK (kind IN ('Copy', 'Recognize')),
origin TEXT NOT NULL CHECK (origin IN ('Manual', 'Automatic')),
state TEXT NOT NULL CHECK (state IN ('Running', 'Interrupted', 'Paused', 'Completed', 'Cancelled')),
started_at INTEGER NOT NULL,
completed_at INTEGER,
last_error TEXT
);
-- Foreign key of the destination.
CREATE INDEX ix_export_run_destination ON export_run (destination_id);
-- Runs to resume at start-up and in the hourly round, without reading the finished ones.
CREATE INDEX ix_export_run_unfinished ON export_run (state) WHERE state IN ('Running', 'Interrupted', 'Paused');
-- A file of an export job (on the model of import_file): what was requested (variant and format as asked: the effective
-- ones are known only on the file and go to export_copy), and how it went.
CREATE TABLE export_item (
id INTEGER PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES export_run (id) ON DELETE CASCADE,
-- The library file; NULL when it was deleted meanwhile (the item then ends «File non presente in libreria»).
media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
-- Effective account; never written NULL, cleared only by the removal of the account.
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
-- SHA-256 of the original when queued; NULL when the file was not in the library.
source_sha256 TEXT CHECK (source_sha256 IS NULL OR length(source_sha256) = 64),
variant TEXT NOT NULL CHECK (variant IN ('Whole', 'Converted', 'Frame')),
format TEXT NOT NULL CHECK (format IN ('Original', 'Jpg', 'Png', 'WebpLossless', 'Mp4')),
frame_at_ms INTEGER CHECK (frame_at_ms IS NULL OR frame_at_ms >= 0),
state TEXT NOT NULL CHECK (state IN ('Pending', 'Copied', 'Adopted', 'AlreadyCopied', 'Skipped', 'Missing', 'Failed')),
-- English code of a note for the report (an animated image copied as original, metadata the format cannot keep).
note TEXT,
-- Target path in the destination, written in its own transaction before the .part is created: the .part left by a
-- crash are removed only in the folders of the items of unfinished runs, never by a scan (spec §4.10).
relative_path TEXT CHECK (relative_path IS NULL OR length(relative_path) > 0),
copy_id INTEGER REFERENCES export_copy (id) ON DELETE SET NULL,
last_error TEXT,
CHECK ((variant = 'Whole' AND format = 'Original')
OR (variant = 'Converted' AND format IN ('Jpg', 'Png', 'WebpLossless', 'Mp4'))
OR (variant = 'Frame' AND format IN ('Jpg', 'Png', 'WebpLossless'))),
CHECK ((variant = 'Frame') = (frame_at_ms IS NOT NULL))
);
-- One item per file and request in a job, so adding the items again on resume adds nothing (ON CONFLICT DO NOTHING).
-- The store never writes a NULL media_id (only the deletion of the file clears it), so NULLs, distinct here, never meet.
CREATE UNIQUE INDEX ux_export_item_file ON export_item (run_id, media_id, variant, format, ifnull(frame_at_ms, -1));
-- Resume, report and .part cleanup: the items of a run by state.
CREATE INDEX ix_export_item_run_state ON export_item (run_id, state);
-- The items of a run by key, whatever their state (report, resume): (run_id, rowid), without a sort at each page.
CREATE INDEX ix_export_item_run ON export_item (run_id);
-- Foreign keys with SET NULL.
CREATE INDEX ix_export_item_media ON export_item (media_id) WHERE media_id IS NOT NULL;
CREATE INDEX ix_export_item_account ON export_item (account_id) WHERE account_id IS NOT NULL;
CREATE INDEX ix_export_item_copy ON export_item (copy_id) WHERE copy_id IS NOT NULL;
-- «È un video fermo?» (spec §4.10, tappa E4): the outcome per SHA-256 of the video and number of the algorithm, so a
-- later algorithm can analyse again. No link to media: the answer outlives deletion and re-import of the same file.
CREATE TABLE video_analysis (
sha256 TEXT NOT NULL CHECK (length(sha256) = 64),
algorithm INTEGER NOT NULL CHECK (algorithm >= 1),
outcome TEXT NOT NULL CHECK (outcome IN ('Still', 'Moving', 'NotAnalyzable')),
analyzed_at INTEGER NOT NULL,
PRIMARY KEY (sha256, algorithm)
) WITHOUT ROWID;
-- A converted file added to an entry by the conversion for the library (spec §4.10, tappa E3; decision of Alberto of
-- 26 November 2026): one row per converted file, linked to the media row of its original, which does not change. SHA-256,
-- perceptual hash, thumbnail, duplicate check and _febe.jsonl stay those of the original; the converted file is never
-- downloaded again and never a duplicate. Pending rows are the queue of the conversion (it resumes from them).
-- RESTRICT: deleting the media row while a record exists fails, so the converted file can never be left on disk
-- unrecorded; tappa E3 deletes the converted files and their rows explicitly (Removed when the entry is remembered).
CREATE TABLE media_conversion (
id INTEGER PRIMARY KEY,
media_id INTEGER NOT NULL REFERENCES media (id) ON DELETE RESTRICT,
format TEXT NOT NULL CHECK (format IN ('Jpg', 'Png', 'WebpLossless', 'Mp4')),
state TEXT NOT NULL CHECK (state IN ('Pending', 'Converted', 'Superseded', 'Removed', 'Failed')),
-- SHA-256 of the original it was made from: when media.sha256 changes, the conversion is Superseded.
source_sha256 TEXT NOT NULL CHECK (length(source_sha256) = 64),
relative_path TEXT CHECK (relative_path IS NULL OR length(relative_path) > 0),
bytes INTEGER CHECK (bytes IS NULL OR bytes >= 0),
sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64),
created_at INTEGER NOT NULL,
converted_at INTEGER,
state_changed_at INTEGER,
last_error TEXT,
-- Every state past Pending and Failed had a converted file.
CHECK (state IN ('Pending', 'Failed')
OR (relative_path IS NOT NULL AND bytes IS NOT NULL AND sha256 IS NOT NULL AND converted_at IS NOT NULL)),
CHECK (sha256 IS NULL OR sha256 <> source_sha256)
);
-- One current conversion per original and format (Superseded and Removed are history).
CREATE UNIQUE INDEX ux_media_conversion_current ON media_conversion (media_id, format) WHERE state IN ('Pending', 'Converted', 'Failed');
-- Foreign key (RESTRICT) and the conversions of an entry's files.
CREATE INDEX ix_media_conversion_media ON media_conversion (media_id, state);
-- A converted file met by download, import or rebuild is recognised by its own SHA-256 and never counted as a duplicate.
CREATE INDEX ix_media_conversion_sha256 ON media_conversion (sha256) WHERE sha256 IS NOT NULL;
-- The queue of the conversion, in order, without reading the finished rows.
CREATE INDEX ix_media_conversion_pending ON media_conversion (id) WHERE state = 'Pending';