E1: schema dell'esportazione, migrazione 0003, archivi ed ExportSettings (#58) #69

Merged
Alby96 merged 2 commits from funzione/esportazione-schema into main 2026-11-26 21:31:33 +01:00
23 changed files with 3756 additions and 7 deletions
Showing only changes of commit ea4666d49b - Show all commits

No files matched your search

+5 -4
View File
@@ -271,12 +271,12 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
- Cartelle rifiutate: dentro **o contenenti** Dati, Libreria, una cartella di account (anche fuori dalla Libreria) o `/importa`; la radice di un disco o di una condivisione. Lettere di unità e percorsi UNC che puntano allo stesso posto si riconoscono con un file di prova, non confrontando i testi: un `.febe-prova-*.part` scritto e tolto come quello del punto qui sotto, **solo nella cartella candidata**, che deve già esistere, e mai in Dati, Libreria, cartelle degli account o `/importa`. Lì Febe lo cerca soltanto, in lettura: risalendo le loro cartelle madri (una di loro è dentro la candidata) e, per ogni cartella madre della candidata, allo stesso percorso relativo sotto ciascuna (la candidata è dentro una di loro). Se il file di prova non si scrive, la cartella si rifiuta. Si ricontrolla quando cambia la cartella di un account.
- **La radice di una destinazione non si crea mai**: un disco o una condivisione assente non deve diventare una cartella locale. Le sottocartelle dello schema sì. Prima di ogni gruppo di copie Febe scrive e toglie un file `.febe-prova-*.part`; se non riesce, la destinazione va in pausa, lo stato si vede in Impostazioni e nella Dashboard e il giro orario riprova. Mai la striscia rossa, che resta del motore. I controlli sul disco esterno sono asincroni e brevi: una condivisione staccata non blocca l'interfaccia.
- Spazio: per le destinazioni non valgono i 10 GB / 5 % della libreria; basta spazio libero per il prossimo file più un margine. Su FAT32 conta il limite di 4 GB per file.
- **Mai sovrascrivere, mai cancellare** (regola 12): si scrive con un `.part`, si verifica lo SHA-256, si rinomina su un nome libero. Togliere una destinazione toglie solo la configurazione («I file già copiati restano dove sono»); eliminare un elemento dalla libreria non tocca le sue copie. I `.part` rimasti si tolgono solo nelle cartelle di lavori non finiti, mai con una scansione della destinazione.
- **Mai sovrascrivere, mai cancellare** (regola 12): si scrive con un `.part`, si verifica lo SHA-256, si rinomina su un nome libero. Togliere una destinazione toglie solo la configurazione («I file già copiati restano dove sono»); le copie registrate restano nel database, legate alla destinazione ritirata; eliminare un elemento dalla libreria non tocca le sue copie. I `.part` rimasti si tolgono solo nelle cartelle di lavori non finiti, mai con una scansione della destinazione.
**Conversione del formato.** Due impostazioni distinte, **entrambe spente** per impostazione predefinita:
- **per le copie**: il formato in cui arrivano i file nella destinazione. Valori predefiniti in Impostazioni → Esportazione, che ogni destinazione e ogni singola «Copia in…» possono cambiare;
- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Come si registra lo fissano le tappe E1 ed E3.
- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3.
| | Scelte | Come |
|---|---|---|
@@ -782,13 +782,14 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc
| `event` | Cronologia leggibile per l'interfaccia |
| `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura |
| `import_run`, `import_file` | Importazioni e loro file, con esito e decisione |
| `export_destination`, `export_copy`, `export_run`, `export_item`, `video_analysis` | **Previste**, migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito; rimuovere un account la disattiva, non la cancella), copie fatte per file, destinazione e account effettivo con il loro stato (§4.10), lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere), esito dell'analisi dei video fermi per SHA-256. Impostazioni in `setting` con chiavi `esportazione.*`; nessuna colonna nuova in `account` |
| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), costruite, ancora non usate da interfaccia e motore: destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account; copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` |
Vincoli che contano:
- `entry` è unico per (account, tipo, identificativo Instagram); `media` per (elemento, posizione). Lo stesso post può comparire sotto due account, come post di uno e come taggato di un altro: sono due elementi e due copie dei file.
- Stati di un elemento: da scaricare, scaricato, parziale, fallito, saltato, importato, eliminato. «Eliminato» resta nel database senza file, perché non venga riscaricato (§4.6).
- Indici su (account, data di pubblicazione), SHA-256, impronta, stato. Dalla migrazione `0002` (tappa D1) anche `ix_entry_discovered` su `entry (discovered_at)`, per le miniature della cronologia della Dashboard (§7.9), e `ix_media_entry_files` su `media (entry_id, state, kind)`, per i conteggi di «Tutte le foto» (§4.6).
- Dalla migrazione `0003` (tappa E1): l'identità di una copia è unica sulle righe correnti, «Copiato» e «Non riuscito» (`ux_export_copy_identity`); un percorso di una destinazione è tenuto al più da una copia «Copiato» o «Superato», senza distinguere le maiuscole ASCII, e un percorso «Tolto» è di nuovo libero (`ux_export_copy_path`); una copia non è mai «Superato» dal suo stesso originale (se il file della libreria torna quello di prima, la copia torna «Copiato»); una cartella senza il suo account non è mai automatica; nella stessa cartella al più una conversione corrente per file e formato (`ux_media_conversion_current`); le ricerche vanno per SHA-256 (`ix_export_copy_sha256`, `ix_export_copy_superseded_by`); il filtro «Copie» su tutta la libreria legge `ix_export_copy_destination`, e le copie di una destinazione e i file di un lavoro si sfogliano per chiave senza riordinarli (`ix_export_copy_destination_id`, `ix_export_item_run`); una destinazione con copie o lavori e una riga `media` con un convertito registrato non si cancellano (`ON DELETE RESTRICT`); ogni colonna di chiave esterna delle tabelle nuove ha il suo indice.
- Versione dello schema in `PRAGMA user_version`, migrazioni come file SQL numerati eseguiti all'avvio dentro una transazione. Un solo scrittore: le scritture passano da una coda.
### 8.4 Miniature e impronte
@@ -1114,7 +1115,7 @@ Ogni tappa finisce con i controlli «Fatto quando» eseguiti e mostrati, `docs/s
| **C4 Decodificatore H.265** | HEVC (ITU-T H.265) nei profili di §3: Main, Main 10, Main Still Picture e le estensioni di formato (RExt) della serie, che restano (risposta di Alberto del 25 novembre 2026, domanda 18 di §16), per fotogrammi, miniature e video fermi come H.264 | §3, §4.10, §8.4 | Tutti i flussi di ITU-T H.265.1 delle cartelle `HEVC_v1` e `RExt`, scaricati con il permesso di Alberto, in `tests/Febe.Tests/Media/H265/Conformita` con il `LEGGIMI.md` della fonte, uguali all'MD5 di riferimento, nessuno saltato |
| **C5 Lettori ASF, FLV e MPEG-PS** | Durata, dimensioni, codec e data dove c'è, per ASF (WMV), FLV e MPEG-PS (ISO/IEC 13818-1), nell'analisi dell'importazione (§9.2) | §3, §9.2 | Prove su file costruiti dalle prove, troncati e rovinati compresi; nessun file reale |
| **C6 Niente terzi nella CI e nell'interfaccia** | CI senza Node (passi di shell con git e curl verso l'API di Gitea), installatore di Windows scritto in casa al posto di NSIS, caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo gitleaks e Trivy nella CI, e Chromium con i suoi pacchetti Debian e Xvfb (regola 13) | §3, §10.1, §12, appendici B e C, `docs/processo.md` | Una verifica verde senza `node` nel contenitore delle prove né azioni che lo vogliano; installatore provato (§14.1); nessun file di Archivo o Lucide nel repository; schermate riconfrontate con i mockup (§10.7), con le differenze dei caratteri scritte; NSIS e Node tolti da `docs/processo.md` e dalla regola 13 |
| **E1 Schema** | Migrazione `0003` (la `0002` è di D1) con le tabelle di §8.3, archivi e impostazioni `esportazione.*`. Nessun cambio di comportamento | §8.3, §4.10 | Database della versione 1 aggiornato con `foreign_key_check` pulito; database più nuovo rifiutato |
| **E1 Schema** | Migrazione `0003` (la `0002` è di D1) con le tabelle di §8.3, `export_account` e `media_conversion` comprese, archivi e `ExportSettings` con le chiavi `esportazione.*`. Nessun cambio di comportamento | §8.3, §4.10 | Database delle versioni 1 e 2 aggiornati con `foreign_key_check` pulito; database più nuovo rifiutato |
| **E2 Copie esterne** | Destinazioni (generale e per account), controlli delle cartelle, `/esporta` in Docker, «Copia in…» degli originali, adozione, stati «Tolto» e «Superato», «già copiato» su tessere, visualizzatore, scheda account e filtro «Copie», scheda «Esportazione» della Dashboard | §4.10, §10.3, §11, §12, §13.2 | Prove: cartelle rifiutate, radice mai creata, `/esporta` non montata quindi nulla scritto, nessuna sovrascrittura, adozione, filtro «Copie» con 200.000 elementi entro 250 ms. Schermate confrontate (§10.7) e guida dell'esportazione |
| **E3 Formati e fotogrammi** | Conversione delle copie e della libreria (il convertito si aggiunge, l'originale resta), metadati copiati, rimuxaggio, fotogrammi a richiesta, zip | §4.10, §3 | Prove: JPG → JPG è una copia, PNG con trasparenza → JPG, WEBP senza perdita con i pixel identici all'originale, metadati presenti nel convertito, MOV → MP4, fotogramma a un istante, ogni k secondi, N; libreria con originale intatto |
| **E4 Video fermi** | Analisi a richiesta, `video_analysis`, «Salva il fotogramma» | §4.10 | Prove su video costruiti dalle prove (immagine fissa con audio, dissolvenza dal nero, movimento, clip brevissima, tutto nero, rotazione); soglie in `docs/decisioni.md` |
+18
View File
@@ -569,3 +569,21 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-25 | Documenti di D1 allineati a ciò che è costruito: §4.6 (la scelta del mosaico resta solo nel browser, a differenza del tema; `mode=grouped` o `files`, cursore `ms.elemento.posizione`, campo `files` di `/api/library/days`), §6.5 e §7.2 (posto su otto al file più vecchio di tutta la coda, reel dalla scheda Reel o da `product_type` «clips», giro primo e storie segnalate davanti, pesi 16/8/4/2/1 da confermare), §7.9 e §10.3 (Dashboard compressa, benvenuto compatto al primo avvio), §8.3 e §15 (D1 ha la migrazione `0002` con `account.download_order`, `entry.is_reel`, `ix_entry_discovered` e `ix_media_entry_files`; E1 prende la `0003`), appendice C (`layout-dashboard` al posto di `activity`, `chevron-up` e `grip-vertical`); guida, prove dal vivo e `windows.md` dicono Dashboard. Al primo avvio la Dashboard mostra il benvenuto compatto finché non c'è nessun account (`/api/accounts` vuoto), con «Collegati a Instagram» o, già collegati, «Aggiungi account», più «Importa foto e video che hai già» | Con D1 `/` apre la Dashboard e il benvenuto della Libreria vuota non era più la prima cosa vista: il benvenuto nello stesso posto in cui si apre Febe è la cosa meno sorprendente, e la condizione «nessun account» copre anche chi si è collegato senza aggiungere nessuno. Le righe precedenti di oggi lasciavano da sistemare §15 («E1: migrazione `0002`») e l'appendice C |
| 2026-11-25 | Due scelte di D1 e di S4b che la specifica dava per decise diventano proposte con una domanda di §16: i 5 secondi di grazia in Docker prima che lasciare la pagina del browser copi la sessione (§6.0 «Quando si copia», domanda 20) e il posto su otto della coda dei file al file che aspetta da più tempo (§6.5, §7.2, domanda 21). Il comportamento costruito resta quello proposto finché Alberto non risponde | Alberto ha detto solo che lasciare la pagina copia la sessione e quale ordine dei tipi vuole: la durata della grazia e la quota del più vecchio sono scelte di chi ha costruito, e `docs/stato.md` le teneva già fra le domande aperte |
| 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana |
| 2026-11-26 | Risposta di Alberto del 26 novembre 2026: le conversioni per la libreria si registrano in una tabella a parte, `media_conversion`, nella migrazione `0003`: una riga per file convertito, legata alla riga `media` dell'originale con `ON DELETE RESTRICT`, con formato, percorso relativo, byte, SHA-256 del convertito, data e stato (`Pending`, `Converted`, `Superseded`, `Removed`, `Failed`: in attesa, convertito, superato, tolto, non riuscito). La tabella `media` non cambia; le righe `Pending` sono la coda della conversione, senza un `export_run` per la libreria | Decisione di Alberto. SHA-256, impronta, miniatura, doppioni e `_febe.jsonl` restano dell'originale (§4.10); con RESTRICT dimenticare il file convertito fa fallire l'eliminazione invece di lasciarlo sul disco senza traccia. La tappa E3 dovrà togliere convertiti e righe prima di toccare `media`, in entrambi i modi di eliminazione |
| 2026-11-26 | Risposta di Alberto del 26 novembre 2026: E1 è migrazione `0003`, record del dominio, archivi (`IExportStore`, `IVideoAnalysisStore`, `IMediaConversionStore`, esposti da `IFebeStorage`) con le loro prove ed `ExportSettings` sulle chiavi `esportazione.*` di `setting`. Nulla li usa ancora in interfaccia, motore o API. L'unico percorso esistente che cambia è `AccountStore.DeleteAsync` (un UPDATE in più, che non fa nulla finché non esistono destinazioni) | Nessun cambio di comportamento (§15, «E1 Schema») |
| 2026-11-26 | Ambito della destinazione salvato come nome inglese dell'enumerazione (`General`, `Account`) invece di `tutti`/`account` | La convenzione dello schema (intestazione della `0001`, `Sql.Enum`); la specifica chiede solo una colonna esplicita per l'ambito |
| 2026-11-26 | Una destinazione è una cartella per sempre: `root_path` obbligatorio e mai cambiato dall'archivio; cambiare cartella o togliere la destinazione la ritira (`removed_at`, «Automatica» spenta) e le copie, i lavori e i loro file restano; `export_copy` ed `export_run` la riferiscono con `ON DELETE RESTRICT`. Al più una cartella generale in uso e una cartella propria in uso per account (indici unici parziali) | «Già copiato» non deve rispondere per una cartella dove le copie non sono mai state scritte; §4.10 «toglie solo la configurazione» e §13.2: `export_copy` è tutto ciò che Febe sa delle copie |
| 2026-11-26 | «Esporta questo account» in una tabella a parte, `export_account` (account, acceso), che se ne va con l'account (CASCADE); nessuna riga: il valore predefinito, che sceglie E2. La cartella generale non ha interruttore: nessuna cartella generale vuol dire nessuna riga generale in uso | È un interruttore dell'account, non di una destinazione, e vale anche con la cartella propria; §8.3 non vuole colonne nuove in `account`, non tabelle |
| 2026-11-26 | Rimozione di un account: `AccountStore.DeleteAsync` scrive il nome dell'account sulle sue destinazioni (in uso e ritirate) e spegne «Automatica» (dimenticando «Solo i nuovi») nella stessa transazione, poi `ON DELETE SET NULL` toglie il legame; la riga in uso resta inattiva, «era di @nome», e se l'account torna `AttachDestinationAsync` gliela ridà con le copie orfane, sempre con «Automatica» spenta (`RelinkOrphanCopyAsync` per una copia orfana adottata di nuovo). Due CHECK (`scope = 'General' OR account_id IS NOT NULL OR removed_account_username IS NOT NULL` e `… OR automatic = 0`) fanno fallire chi cancella un account senza scrivere il nome o senza spegnere «Automatica»; `UpdateDestinationAsync` rifiuta di accenderla su una cartella senza account. Nessun trigger | È l'unico percorso che cancella un account; il CHECK vale anche sull'azione SET NULL (provato da `RawAccountDeleteWithoutUserNameFails`). «Disattiva» (risposta di Alberto del 18 novembre) vuol dire «Automatica» spenta: senza, l'account aggiunto di nuovo riavrebbe la copia automatica con il vecchio «Solo i nuovi», senza la domanda della prima accensione (§4.10) |
| 2026-11-26 | Identità della copia con variante e formato **effettivi** (un risultato byte per byte è sempre «intero» in Originale: un CHECK vuole lo SHA-256 della copia uguale a quello dell'originale per le copie intere, e solo per loro), unica solo sulle righe correnti, `Copied` e `Failed` (`ux_export_copy_identity`). «Copia di nuovo» aggiunge una riga; la riga più recente di un'identità in qualunque stato (`FindLatestCopyAsync`) decide se si può accodare da sola: `Removed` e `Superseded` no | §4.10: un file si copia una volta sola; «Tolto» e «Superato» non si ricopiano mai da soli |
| 2026-11-26 | «Superato» con `superseded_by_sha256`, lo SHA-256 del file che ha preso il posto dell'originale in libreria: obbligatorio su `Superseded`, ammesso su `Removed`, per account; `SupersedeCopiesAsync` lo sposta in avanti se il file cambia ancora | «Tieni il più grande» tiene la riga `media` e ne cambia lo SHA-256 (`ImportCopier`): il file nuovo non deve sembrare «non ancora copiato» e accodarsi da solo; la ricerca resta per SHA-256 e regge anche «Eliminalo e lascia che torni» |
| 2026-11-26 | Percorsi delle copie con `COLLATE NOCASE`, separati da `/` e in forma NFC (l'archivio li normalizza, anche nella ricerca per percorso); NOCASE confronta senza maiuscole solo le lettere ASCII. Un percorso con una copia `Copied` o `Superseded` è occupato, uno `Removed` è di nuovo libero (`ux_export_copy_path`) | Destinazioni Windows e SMB, dove due nomi che differiscono per le maiuscole sono lo stesso file: mai due righe su un file |
| 2026-11-26 | `export_copy` sopravvive all'eliminazione dell'elemento e dei file (`media_id` con SET NULL, `source_sha256` obbligatorio); l'archivio non scrive mai NULL nell'account di una copia o di un file di lavoro (`AddCopyAsync` e `AddItemsAsync` lo rifiutano, `UpdateCopyAsync` non tocca l'identità) | §4.10: «ritrova le sue copie quando torna»; NULL nell'identità vuol dire solo «orfana», e due copie orfane con la stessa identità restano entrambe |
| 2026-11-26 | Cinque chiavi `esportazione.*` (`formato-foto`, `formato-video`, `libreria-formato-foto`, `libreria-formato-video`, `stesso-post`) con i nomi inglesi dei valori, letti esattamente (non `Enum.TryParse`, che accetta numeri ed elenchi) e con ripiego per chiave sul predefinito; un formato del tipo sbagliato vale Originale. Tutto Originale e «Una copia per account» per impostazione predefinita; qualità JPG 92 costante. Cartella generale, tipi, tre schemi dei nomi (generale, raccolte, foto del profilo, come §4.7) e «Automatica» stanno nella riga `General` di `export_destination`, non in `setting`; né l'avvio né la migrazione scrivono chiavi | Come `motore.profilo` e `LibrarySettings`; §4.10: conversioni spente, perdita solo se scelta |
| 2026-11-26 | «Solo i nuovi»: `automatic_since` confrontato con `media.downloaded_at`, l'ora della riga di `_febe.jsonl` che la ricostruzione rimette; spegnere «Automatica» dimentica la risposta (un CHECK) e la prossima accensione chiede di nuovo | §4.10 «Quando Alberto l'accende» e «dopo la sua riga di `_febe.jsonl`» |
| 2026-11-26 | `video_analysis` con chiave (SHA-256, algoritmo), senza legame a `media`; vale l'algoritmo più alto | L'esito sopravvive all'eliminazione e alla reimportazione dello stesso file; un algoritmo nuovo può rianalizzare senza cancellare |
| 2026-11-26 | Indici per E2: `ix_export_copy_destination (destination_id, state, source_sha256, account_id)` per il filtro «Copie» su tutta la libreria nella forma a insieme (0,19 s contro 1,3-2,1 s dell'EXISTS per elemento, banco di 200.000 elementi, 240.000 file, 80.000 copie), `ix_export_copy_sha256` per le finestre, il visualizzatore e la riga più recente di un'identità, `ix_export_copy_superseded_by` per «Tolti o superati»; nessun indice su `media` nella `0003` | La scelta già fatta per «Foto»/«Video» (2026-11-25); `media` non cambia (risposta di oggi); E2 misura in `LibraryScaleTests` e aggiunge `media (sha256, entry_id)` in una migrazione sua solo se serve |
| 2026-11-26 | In più al progetto di E1: `ix_export_copy_destination_id (destination_id)` ed `ix_export_item_run (run_id)`, e `+state` nella pagina delle copie di una destinazione con uno stato, così `ListCopiesAsync` e `ListItemsAsync` vanno per chiave senza un ordinamento temporaneo a ogni pagina | Con i soli indici del progetto il piano di quelle due domande era `USE TEMP B-TREE FOR ORDER BY`: ogni pagina rileggeva e riordinava tutte le copie della destinazione o tutti i file del lavoro. `ExportLookupsUseTheirIndex` lo controlla con e senza ANALYZE |
| 2026-11-26 | `export_item` tiene la richiesta (variante e formato chiesti), `export_copy` il risultato effettivo; il percorso di arrivo di un file si scrive nella sua transazione prima di creare il `.part`; aggiungere di nuovo gli stessi file a un lavoro non aggiunge nulla (`ux_export_item_file`, `ON CONFLICT DO NOTHING`). `AddItemsAsync` rifiuta un file senza `media_id` (in un indice unico i NULL sono tutti diversi, e lo stesso file si aggiungerebbe due volte) e `UpdateItemsAsync` non riscrive mai lavoro, file, variante, formato e istante: `ArgumentException` se cambiano; il file si toglie solo con la sua eliminazione (SET NULL) | La ripresa riaggiunge le stesse richieste; i `.part` si tolgono solo nelle cartelle dei file dei lavori non finiti (§4.10), mai con una scansione |
| 2026-11-26 | Il file della libreria torna quello di prima (A→B→A, o A→B→C→A): `SupersedeCopiesAsync(B, A)` non segna mai una copia come superata dal suo stesso originale (un CHECK `superseded_by_sha256 <> source_sha256`). Le copie «Superato» di A tornano «Copiato» (la più recente per identità; le altre restano «Superato» da B, come storia) se l'identità non ha già una riga corrente, copiata di nuovo nel frattempo o non riuscita: allora restano «Superato» da B; le «Tolto» perdono solo il segno | «Tieni il più grande» confronta i pixel quando entrambe le dimensioni sono note e altrimenti i byte (`ImportPlanner.IsLarger`), quindi non è transitivo; anche una ricostruzione tiene il file sul disco. Una copia uguale byte per byte al file della libreria è copiata, non superata, e non deve restare bloccata per sempre; l'indice unico vuole al più una riga corrente per identità, e la riga corrente già presente risponde per quella copia |
| 2026-11-26 | Le collisioni con gli indici unici della `0003` (cartella generale o cartella propria in uso, identità corrente e percorso di una copia, conversione corrente) arrivano a chi chiama come `DuplicateRecordException`, il tipo di `Febe.Core` già usato da `AccountStore` ed `EntryStore`, mai come `SqliteException` | `Febe.Core` non conosce Microsoft.Data.Sqlite: E2 ed E3 devono poter riconoscere il caso (per esempio un percorso già preso) senza rompere i livelli, e l'API risponderlo come conflitto invece di un errore 500 |
+36 -1
View File
@@ -1,13 +1,48 @@
# Stato
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
Aggiornato il 26 novembre 2026 (catena della 0.3.0 unita in `main`, #60 … #66), versione 0.1.2 in
Aggiornato il 26 novembre 2026 (tappa E1 Schema sul ramo `funzione/esportazione-schema`; prima, catena della 0.3.0
unita in `main`, #60 … #66), versione 0.1.2 in
`main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
fra le sessioni; ciò che è da fare si legge nelle issue aperte.
## In breve
**26 novembre 2026: tappa E1 «Schema» dell'esportazione** (#58, ramo `funzione/esportazione-schema`). Nessun cambio di
comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue.
- **Migrazione `0003_esportazione.sql`**: `export_destination` (cartella generale o di un account, una cartella per
sempre, ritirata invece che cancellata), `export_account` («Esporta questo account»), `export_copy` (identità con
SHA-256 dell'originale, destinazione, account effettivo, variante, formato e istante; stati Copiato, Tolto, Superato,
Non riuscito; sopravvive all'eliminazione dell'elemento), `export_run` ed `export_item` (sul modello
dell'importazione), `video_analysis` (per SHA-256 e algoritmo) e `media_conversion` (decisione di Alberto di oggi: i
convertiti per la libreria in una tabella a parte, `media` non cambia). Indici per E2 spiegati nella migrazione e in
`decisioni.md`.
- **Archivi** in `IFebeStorage`: `IExportStore`, `IVideoAnalysisStore`, `IMediaConversionStore`; **`ExportSettings`**
sulle cinque chiavi `esportazione.*` di `setting` (tutto Originale, «Una copia per account»; né l'avvio né la
migrazione scrivono chiavi).
- L'unico percorso esistente che cambia è `AccountStore.DeleteAsync`: prima di cancellare l'account spegne «Automatica»
delle sue cartelle (dimenticando «Solo i nuovi») e vi scrive il suo nome; finché non ci sono destinazioni non fa nulla.
- Correzioni della revisione, prima del commit: la rimozione di un account disattiva davvero la sua cartella (anche
quando torna), una copia non è mai «Superato» dal suo stesso originale (A→B→A torna «Copiato»), un file di lavoro ha
sempre il suo file della libreria, le collisioni con gli indici unici arrivano come `DuplicateRecordException`, le
prove dei vincoli isolano ciascun CHECK e la prova dell'aggiornamento riempie tutte le quindici tabelle della
versione 1. Righe in `decisioni.md`.
- Controlli, su Windows: `dotnet build -warnaserror` 0 avvisi, 0 errori; `dotnet test tests/Febe.Tests` 2875 superate,
96 ignorate (quelle con Chromium e Xvfb, solo nella CI), 0 non superate; `dotnet test tests/Febe.Tests.Windows` 24
superate.
- **Lasciato a E2 ed E3**:
- il valore predefinito di «Esporta questo account» (nessuna riga in `export_account` oggi: lo sceglie E2);
- E3 deve togliere i file convertiti e le righe di `media_conversion` prima di cancellare una riga `media`
(`ON DELETE RESTRICT`): oggi `LibraryDeletion` e la rimozione di un account con un convertito registrato
falliscono, ed è voluto (nessun convertito resta sul disco senza traccia);
- E2 misura il filtro «Copie» in `LibraryScaleTests` (200.000 elementi entro 250 ms) e aggiunge `media (sha256,
entry_id)` in una migrazione sua solo se serve;
- Docker `/esporta` e i controlli delle cartelle sono di E2.
- **Non verificato**: la CI del ramo (nessun push); nessun database vero di Alberto aggiornato, solo quelli costruiti
dalle prove alle versioni 1 e 2.
**26 novembre 2026: la catena della 0.3.0 è unita in `main`** (#58, #59, #36). Sette rami, ognuno con l'unione del
precedente, ciascuno con la sua richiesta di unione (#60 … #66), uniti in questo ordine, uno alla volta, ciascuno dopo
la sua verifica verde nella CI (`docs/processo.md`). `main` è protetto e rifiuta un ramo indietro: dopo ogni unione il
+381
View File
@@ -0,0 +1,381 @@
namespace Febe.Core.Domain;
/// <summary>Scope of an export destination (spec §4.10 «Destinazioni»).</summary>
public enum ExportScope
{
/// <summary>«Cartella di esportazione generale»: every account, each under its own segment.</summary>
General,
/// <summary>«Cartella propria» of one account, which replaces the general folder for that account.</summary>
Account,
}
/// <summary>Format of an exported file or of a converted library file (spec §4.10 «Conversione del formato»).</summary>
public enum ExportFormat
{
/// <summary>«Originale»: the file as it is in the library, byte for byte.</summary>
Original,
/// <summary>JPG, quality 92: the only lossy choice («con perdita»).</summary>
Jpg,
/// <summary>PNG.</summary>
Png,
/// <summary>«WEBP senza perdita».</summary>
WebpLossless,
/// <summary>MP4, by remuxing only.</summary>
Mp4,
}
/// <summary>Which formats belong to photos and which to videos.</summary>
public static class ExportFormats
{
/// <summary>Originale, JPG, PNG, WEBP senza perdita.</summary>
public static bool IsPhotoFormat(ExportFormat format) =>
format is ExportFormat.Original or ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless;
/// <summary>Originale, MP4.</summary>
public static bool IsVideoFormat(ExportFormat format) => format is ExportFormat.Original or ExportFormat.Mp4;
}
/// <summary>What an export writes from a library file.</summary>
public enum ExportVariant
{
/// <summary>«Intero»: the whole file, byte for byte (format Original).</summary>
Whole,
/// <summary>«Convertito»: the file in another format.</summary>
Converted,
/// <summary>«Fotogramma»: a picture of a video at an instant.</summary>
Frame,
}
/// <summary>State of a copy in a destination (spec §4.10 «Già copiato»).</summary>
public enum ExportCopyState
{
/// <summary>«Copiato».</summary>
Copied,
/// <summary>«Tolto»: the file is no longer in the destination. Never copied again by itself.</summary>
Removed,
/// <summary>«Superato»: the library file changed after the copy. Never copied again by itself.</summary>
Superseded,
/// <summary>«Non riuscito».</summary>
Failed,
}
/// <summary>How a copy came to be recorded.</summary>
public enum ExportCopyOrigin
{
/// <summary>Written by Febe.</summary>
Written,
/// <summary>An existing file recognised by path (spec §4.10 «Adozione per percorso»).</summary>
Adopted,
}
/// <summary>Kind of an export job.</summary>
public enum ExportRunKind
{
/// <summary>«Copia in…» or the automatic export.</summary>
Copy,
/// <summary>«Riconosci le copie già presenti».</summary>
Recognize,
}
/// <summary>Who started an export job.</summary>
public enum ExportRunOrigin
{
Manual,
Automatic,
}
/// <summary>State of an export job (on the model of <see cref="ImportRunState"/>).</summary>
public enum ExportRunState
{
Running,
/// <summary>Febe was closed: resumes from the pending items.</summary>
Interrupted,
/// <summary>The destination is not reachable: resumes when a later check succeeds.</summary>
Paused,
Completed,
Cancelled,
}
/// <summary>Progress of one file of an export job.</summary>
public enum ExportItemState
{
Pending,
/// <summary>Written to the destination.</summary>
Copied,
/// <summary>An existing file recognised by path.</summary>
Adopted,
/// <summary>«Già copiato»: nothing to do.</summary>
AlreadyCopied,
Skipped,
/// <summary>«File non presente in libreria».</summary>
Missing,
/// <summary>«Non riuscito».</summary>
Failed,
}
/// <summary>Outcome of «È un video fermo?» (spec §4.10).</summary>
public enum VideoAnalysisOutcome
{
/// <summary>«Fermo».</summary>
Still,
/// <summary>«In movimento».</summary>
Moving,
/// <summary>«Non analizzabile».</summary>
NotAnalyzable,
}
/// <summary>State of a converted file added to an entry by the conversion for the library.</summary>
public enum MediaConversionState
{
/// <summary>«In attesa»: the queue of the conversion.</summary>
Pending,
/// <summary>«Convertito».</summary>
Converted,
/// <summary>«Superato»: the original changed after the conversion.</summary>
Superseded,
/// <summary>«Tolto»: the converted file was deleted with its remembered entry.</summary>
Removed,
/// <summary>«Non riuscito».</summary>
Failed,
}
/// <summary>
/// An export destination (spec §8.3 <c>export_destination</c>): the general folder or the own folder of an account.
/// One row is one root folder for ever: another folder is a new row, and the old one is retired with its copies.
/// </summary>
public sealed record ExportDestination
{
public long Id { get; init; }
public required ExportScope Scope { get; init; }
/// <summary>The account of an own folder; null for the general folder, and after the account was removed.</summary>
public long? AccountId { get; init; }
/// <summary>User name of the account when it was removed («era di @nome»). Written only by the account removal.</summary>
public string? RemovedAccountUsername { get; init; }
/// <summary>Name shown in the interface; null: the last segment of <see cref="RootPath"/>.</summary>
public string? Label { get; init; }
/// <summary>Root folder as chosen. Never created by Febe, never changed.</summary>
public required string RootPath { get; init; }
public required ContentTypes ContentTypes { get; init; }
/// <summary>Null: «Come le impostazioni generali».</summary>
public ExportFormat? PhotoFormat { get; init; }
/// <summary>Null: «Come le impostazioni generali».</summary>
public ExportFormat? VideoFormat { get; init; }
/// <summary>General naming scheme under the destination; null: «Come la libreria».</summary>
public string? NamingScheme { get; init; }
/// <summary>Naming scheme of highlight collections; null: «Come la libreria».</summary>
public string? HighlightNamingScheme { get; init; }
/// <summary>Naming scheme of profile pictures; null: «Come la libreria».</summary>
public string? ProfileNamingScheme { get; init; }
/// <summary>«Automatica» (off by default).</summary>
public bool Automatic { get; init; }
/// <summary>
/// «Solo i nuovi»: files downloaded at or after this instant; null with <see cref="Automatic"/>: everything. Must
/// be null when <see cref="Automatic"/> is off.
/// </summary>
public DateTimeOffset? AutomaticSince { get; init; }
/// <summary>The probe file could not be written: paused until a later check succeeds.</summary>
public DateTimeOffset? PausedAt { get; init; }
public string? LastError { get; init; }
public required DateTimeOffset CreatedAt { get; init; }
/// <summary>Retired: removed by Alberto, or replaced by a row with another folder.</summary>
public DateTimeOffset? RemovedAt { get; init; }
public bool IsRetired => RemovedAt is not null;
/// <summary>An own folder whose account was removed.</summary>
public bool IsOrphan => Scope == ExportScope.Account && AccountId is null;
}
/// <summary>
/// The identity of a copy: SHA-256 of the original, destination, effective account, variant, format and frame instant,
/// always the effective ones (a byte-for-byte result is <see cref="ExportVariant.Whole"/> and
/// <see cref="ExportFormat.Original"/> whatever was requested).
/// </summary>
public sealed record ExportCopyIdentity(long DestinationId, long AccountId, string SourceSha256, ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt);
/// <summary>A copy made in a destination (spec §8.3 <c>export_copy</c>). It outlives the library entry.</summary>
public sealed record ExportCopy
{
public long Id { get; init; }
public required long DestinationId { get; init; }
/// <summary>Effective account; null only after the account was removed («orphan»).</summary>
public long? AccountId { get; init; }
/// <summary>The library file; null after the entry or its files were deleted.</summary>
public long? MediaId { get; init; }
public required string SourceSha256 { get; init; }
public required ExportVariant Variant { get; init; }
public ExportFormat Format { get; init; } = ExportFormat.Original;
/// <summary>Instant of a frame; set only for <see cref="ExportVariant.Frame"/>.</summary>
public TimeSpan? FrameAt { get; init; }
public required ExportCopyState State { get; init; }
/// <summary>SHA-256 of the library file that took the place of the original: required for Superseded, allowed on Removed.</summary>
public string? SupersededBySha256 { get; init; }
public ExportCopyOrigin Origin { get; init; } = ExportCopyOrigin.Written;
/// <summary>Path relative to the destination root, '/' separated, NFC.</summary>
public string? RelativePath { get; init; }
public long? Bytes { get; init; }
public string? CopySha256 { get; init; }
public required DateTimeOffset CopiedAt { get; init; }
public DateTimeOffset? StateChangedAt { get; init; }
public string? LastError { get; init; }
/// <summary>The identity of the copy; null for an orphan row.</summary>
public ExportCopyIdentity? Identity =>
AccountId is { } account ? new ExportCopyIdentity(DestinationId, account, SourceSha256, Variant, Format, FrameAt) : null;
}
/// <summary>An export job (spec §8.3 <c>export_run</c>, on the model of <see cref="ImportRun"/>).</summary>
public sealed record ExportRun
{
public long Id { get; init; }
public required long DestinationId { get; init; }
public ExportRunKind Kind { get; init; } = ExportRunKind.Copy;
public ExportRunOrigin Origin { get; init; } = ExportRunOrigin.Manual;
public ExportRunState State { get; init; } = ExportRunState.Running;
public required DateTimeOffset StartedAt { get; init; }
public DateTimeOffset? CompletedAt { get; init; }
public string? LastError { get; init; }
}
/// <summary>
/// A file of an export job (spec §8.3 <c>export_item</c>, on the model of <see cref="ImportFile"/>): the request
/// (variant and format as asked) and how it went; the effective result goes to <see cref="ExportCopy"/>.
/// </summary>
public sealed record ExportItem
{
public long Id { get; init; }
public required long RunId { get; init; }
/// <summary>The library file; null when it was deleted meanwhile.</summary>
public long? MediaId { get; init; }
/// <summary>Effective account; required when the item is added.</summary>
public long? AccountId { get; init; }
/// <summary>SHA-256 of the original when queued; null when the file was not in the library.</summary>
public string? SourceSha256 { get; init; }
public ExportVariant Variant { get; init; } = ExportVariant.Whole;
public ExportFormat Format { get; init; } = ExportFormat.Original;
public TimeSpan? FrameAt { get; init; }
public ExportItemState State { get; init; } = ExportItemState.Pending;
/// <summary>English code of a note for the report.</summary>
public string? Note { get; init; }
/// <summary>Target path in the destination, written before the <c>.part</c> is created.</summary>
public string? RelativePath { get; init; }
public long? CopyId { get; init; }
public string? LastError { get; init; }
}
/// <summary>Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 <c>video_analysis</c>).</summary>
public sealed record VideoAnalysis(string Sha256, int Algorithm, VideoAnalysisOutcome Outcome, DateTimeOffset AnalyzedAt);
/// <summary>
/// A converted file added to an entry by the conversion for the library (spec §4.10, §8.3 <c>media_conversion</c>),
/// linked to the media row of its original, which does not change.
/// </summary>
public sealed record MediaConversion
{
public long Id { get; init; }
public required long MediaId { get; init; }
public required ExportFormat Format { get; init; }
public MediaConversionState State { get; init; } = MediaConversionState.Pending;
/// <summary>SHA-256 of the original it was made from.</summary>
public required string SourceSha256 { get; init; }
/// <summary>Path relative to the account folder, like <see cref="Media.RelativePath"/>.</summary>
public string? RelativePath { get; init; }
public long? Bytes { get; init; }
/// <summary>SHA-256 of the converted file.</summary>
public string? Sha256 { get; init; }
public required DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset? ConvertedAt { get; init; }
public DateTimeOffset? StateChangedAt { get; init; }
public string? LastError { get; init; }
}
+102
View File
@@ -0,0 +1,102 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>Setting keys of Impostazioni → Esportazione (spec §4.10). Values are the English names of the enumerations.</summary>
public static class ExportSettingKeys
{
/// <summary>Format of the copies of photos (Original, Jpg, Png, WebpLossless).</summary>
public const string PhotoFormat = "esportazione.formato-foto";
/// <summary>Format of the copies of videos (Original, Mp4).</summary>
public const string VideoFormat = "esportazione.formato-video";
/// <summary>Conversion of photos for the library; Original: off.</summary>
public const string LibraryPhotoFormat = "esportazione.libreria-formato-foto";
/// <summary>Conversion of videos for the library; Original: off.</summary>
public const string LibraryVideoFormat = "esportazione.libreria-formato-video";
/// <summary>The same post in two accounts: «Una copia per account» or «Una copia sola».</summary>
public const string SamePost = "esportazione.stesso-post";
public static IReadOnlyList<string> All { get; } = [PhotoFormat, VideoFormat, LibraryPhotoFormat, LibraryVideoFormat, SamePost];
}
/// <summary>How many copies the same post gets when it is in two accounts (spec §4.10).</summary>
public enum SamePostCopies
{
/// <summary>«Una copia per account» (default).</summary>
OnePerAccount,
/// <summary>«Una copia sola».</summary>
OneOnly,
}
/// <summary>
/// General settings of the export (spec §4.10, Impostazioni → Esportazione), in the <c>setting</c> table. Both
/// conversions are off by default. The general folder, its content types, naming schemes and «Automatica» are columns
/// of the general destination, not settings.
/// </summary>
public sealed record ExportSettings(
ExportFormat PhotoFormat = ExportFormat.Original,
ExportFormat VideoFormat = ExportFormat.Original,
ExportFormat LibraryPhotoFormat = ExportFormat.Original,
ExportFormat LibraryVideoFormat = ExportFormat.Original,
SamePostCopies SamePost = SamePostCopies.OnePerAccount)
{
/// <summary>Quality of the only lossy conversion, JPG (spec §4.10): fixed, not a setting.</summary>
public const int JpegQuality = 92;
public static ExportSettings Default { get; } = new();
/// <summary>The conversion for the copies is on for photos or videos.</summary>
public bool ConvertsCopies => PhotoFormat != ExportFormat.Original || VideoFormat != ExportFormat.Original;
/// <summary>The conversion for the library is on for photos or videos.</summary>
public bool ConvertsLibrary => LibraryPhotoFormat != ExportFormat.Original || LibraryVideoFormat != ExportFormat.Original;
/// <summary>Loads the settings in one read. A missing or invalid value gives that key's default; the others are not affected.</summary>
public static async Task<ExportSettings> LoadAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
return From(await store.GetAllAsync(ct).ConfigureAwait(false));
}
/// <summary>Stores the five keys in one transaction.</summary>
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
return store.SetManyAsync(
new Dictionary<string, string?>
{
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
[ExportSettingKeys.SamePost] = SamePost.ToString(),
},
ct);
}
/// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
{
ArgumentNullException.ThrowIfNull(values);
ExportFormat Format(string key, Func<ExportFormat, bool> fits) =>
Parse<ExportFormat>(values.GetValueOrDefault(key)) is { } format && fits(format) ? format : ExportFormat.Original;
return new ExportSettings(
Format(ExportSettingKeys.PhotoFormat, ExportFormats.IsPhotoFormat),
Format(ExportSettingKeys.VideoFormat, ExportFormats.IsVideoFormat),
Format(ExportSettingKeys.LibraryPhotoFormat, ExportFormats.IsPhotoFormat),
Format(ExportSettingKeys.LibraryVideoFormat, ExportFormats.IsVideoFormat),
Parse<SamePostCopies>(values.GetValueOrDefault(ExportSettingKeys.SamePost)) ?? SamePostCopies.OnePerAccount);
}
// Not Enum.TryParse: it accepts numbers («2») and lists («Jpg, Png») and returns values that are not names.
private static T? Parse<T>(string? text)
where T : struct, Enum =>
text is not null && Enum.GetNames<T>().Contains(text, StringComparer.Ordinal) ? Enum.Parse<T>(text, ignoreCase: false) : null;
}
+2 -1
View File
@@ -60,7 +60,8 @@ public interface IAccountStore
/// <summary>
/// Removes the account record and, by cascade, its entries, files records and highlights. Files on disk are not
/// touched: removing an account with its files is a library operation, and the default is to keep them and make
/// the account «Solo archivio» (spec §4.2).
/// the account «Solo archivio» (spec §4.2). Its export destinations stay, without account and with the user name;
/// its «Esporta questo account» choice goes with it (spec §4.10).
/// </summary>
Task DeleteAsync(long accountId, CancellationToken ct = default);
}
+173
View File
@@ -0,0 +1,173 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// Export destinations, the switch «Esporta questo account», copies, jobs and their files (spec §4.10; §8.3
/// <c>export_destination</c>, <c>export_account</c>, <c>export_copy</c>, <c>export_run</c>, <c>export_item</c>).
/// Only records: no method touches a file.
/// </summary>
public interface IExportStore
{
// Destinations ---------------------------------------------------------------------------------------------------
/// <summary>
/// Adds a destination. General: <see cref="ExportDestination.AccountId"/> null; Account: set.
/// <see cref="ExportDestination.RemovedAt"/> and <see cref="ExportDestination.RemovedAccountUsername"/> must be null.
/// <see cref="DuplicateRecordException"/> when a general folder is already in use, or the account already has an own
/// folder in use (retire it first).
/// </summary>
Task<ExportDestination> AddDestinationAsync(ExportDestination destination, CancellationToken ct = default);
/// <summary>
/// Writes label, content types, formats, naming schemes, «Automatica» and its answer, pause and error.
/// <see cref="KeyNotFoundException"/> for a missing id; <see cref="ArgumentException"/> if scope, account or root
/// differ from the stored row, the row is retired, or «Automatica» is turned on for an own folder whose account was
/// removed (it is attached to an account first).
/// </summary>
Task UpdateDestinationAsync(ExportDestination destination, CancellationToken ct = default);
Task<ExportDestination?> GetDestinationAsync(long id, CancellationToken ct = default);
/// <summary>The general folder in use, or null.</summary>
Task<ExportDestination?> GetGeneralDestinationAsync(CancellationToken ct = default);
/// <summary>The own folder in use of an account, or null.</summary>
Task<ExportDestination?> GetAccountDestinationAsync(long accountId, CancellationToken ct = default);
/// <summary>The general folder first, then by id; retired rows only when asked.</summary>
Task<IReadOnlyList<ExportDestination>> ListDestinationsAsync(bool includeRetired = false, CancellationToken ct = default);
/// <summary>
/// Retires a destination (removed by Alberto, or replaced by another folder): sets the removal time and turns
/// «Automatica» off. No row and no file is deleted. <see cref="KeyNotFoundException"/> for a missing id.
/// </summary>
Task RetireDestinationAsync(long id, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// Gives an orphan own folder in use back to a re-added account: sets the account, clears the user name and, in the
/// same transaction, sets the account on its orphan copies. «Automatica» stays off (the removal of the account turned
/// it off and forgot «Solo i nuovi»), so turning it on again asks. <see cref="InvalidOperationException"/> if it is not
/// an orphan in use, or the account already has an own folder in use; <see cref="DuplicateRecordException"/> if an
/// orphan copy would collide with a current copy of the account.
/// </summary>
Task AttachDestinationAsync(long id, long accountId, CancellationToken ct = default);
// «Esporta questo account» ---------------------------------------------------------------------------------------
/// <summary>The choice of the account; null when none is recorded (the default applies).</summary>
Task<bool?> GetAccountExportEnabledAsync(long accountId, CancellationToken ct = default);
Task SetAccountExportEnabledAsync(long accountId, bool enabled, CancellationToken ct = default);
// Copies ---------------------------------------------------------------------------------------------------------
/// <summary>
/// Records a copy. <see cref="ArgumentException"/> when the account is null (only the removal of an account clears it);
/// <see cref="DuplicateRecordException"/> when its identity already has a current (Copied or Failed) row, or its path
/// in the destination is held by a Copied or Superseded row.
/// </summary>
Task<ExportCopy> AddCopyAsync(ExportCopy copy, CancellationToken ct = default);
/// <summary>
/// Writes state, superseded-by, media, origin, path, bytes, copy SHA-256, state time and error.
/// <see cref="KeyNotFoundException"/> for a missing id; <see cref="ArgumentException"/> if an identity column
/// (destination, account, source SHA-256, variant, format, frame) differs from the stored row;
/// <see cref="DuplicateRecordException"/> when the new state collides with another current row or path (as in
/// <see cref="AddCopyAsync"/>).
/// </summary>
Task UpdateCopyAsync(ExportCopy copy, CancellationToken ct = default);
Task<ExportCopy?> GetCopyAsync(long id, CancellationToken ct = default);
/// <summary>The current (Copied or Failed) copy of an identity.</summary>
Task<ExportCopy?> FindCurrentCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default);
/// <summary>The newest row of an identity in any state: Removed or Superseded means «never queued by itself».</summary>
Task<ExportCopy?> FindLatestCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default);
/// <summary>Every copy whose original has this SHA-256 or was replaced by it, any destination, account and state, newest first.</summary>
Task<IReadOnlyList<ExportCopy>> ListCopiesBySha256Async(string sha256, CancellationToken ct = default);
/// <summary>The Copied or Superseded copy recorded on this path of a destination (case-insensitive for ASCII).</summary>
Task<ExportCopy?> FindCopyByPathAsync(long destinationId, string relativePath, CancellationToken ct = default);
/// <summary>Copies of a destination by key, with an optional state.</summary>
Task<IReadOnlyList<ExportCopy>> ListCopiesAsync(long destinationId, ExportCopyState? state = null, long afterId = 0, int limit = 500, CancellationToken ct = default);
/// <summary>Counts per state of a destination; every state is present, zero included.</summary>
Task<IReadOnlyDictionary<ExportCopyState, int>> CountCopiesAsync(long destinationId, CancellationToken ct = default);
/// <summary>
/// Re-links an orphan row (account removed) to a re-added account, when its file is adopted again.
/// <see cref="KeyNotFoundException"/> for a missing id; <see cref="InvalidOperationException"/> if the row is not an orphan;
/// <see cref="DuplicateRecordException"/> if the account already has a current copy of that identity.
/// </summary>
Task<ExportCopy> RelinkOrphanCopyAsync(long copyId, long accountId, long? mediaId, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// The library file of an account changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/>: its
/// Copied rows of the old file become Superseded, its Removed rows of the old file get the new SHA-256, and its rows
/// superseded by the old file move to the new one. A row whose own original is the new file (the library went back to
/// it, A→B→A) is never superseded by itself: a Removed one loses the stamp, and the newest Superseded one of each
/// identity becomes Copied again, unless that identity already has a current row (then it stays Superseded by the old
/// file, as history). Returns the rows changed. The caller calls it only when no present file of that account still
/// has the old SHA-256.
/// </summary>
Task<int> SupersedeCopiesAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default);
// Jobs and their files -------------------------------------------------------------------------------------------
Task<ExportRun> CreateRunAsync(ExportRun run, CancellationToken ct = default);
Task UpdateRunAsync(ExportRun run, CancellationToken ct = default);
Task<ExportRun?> GetRunAsync(long runId, CancellationToken ct = default);
/// <summary>Jobs, newest first.</summary>
Task<IReadOnlyList<ExportRun>> ListRunsAsync(CancellationToken ct = default);
/// <summary>Running, Interrupted and Paused jobs, oldest first.</summary>
Task<IReadOnlyList<ExportRun>> ListUnfinishedRunsAsync(CancellationToken ct = default);
/// <summary>
/// Adds items in one transaction; an item already there for the same job, file, variant, format and frame is left
/// unchanged (so a resumed job adds nothing twice). <see cref="ArgumentException"/> when an item has no account or no
/// library file (only the deletion of the file clears it, and an item without one would not be recognised again).
/// </summary>
Task AddItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default);
/// <summary>
/// Writes account (never cleared), source SHA-256, state, note, path, copy and error of items. Job, file, variant,
/// format and frame are the identity of an item and are never rewritten: <see cref="ArgumentException"/> if they
/// differ from the stored row (a file deleted meanwhile stays cleared); <see cref="KeyNotFoundException"/> for a
/// missing item of the job.
/// </summary>
Task UpdateItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default);
Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default);
/// <summary>Items of a job, by key, with an optional state.</summary>
Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default);
/// <summary>Counts by state of a job's items; every state is present, zero included.</summary>
Task<ExportRunSummary> GetRunSummaryAsync(long runId, CancellationToken ct = default);
/// <summary>Removes a job with its items. Only records: copies stay.</summary>
Task DeleteRunAsync(long runId, CancellationToken ct = default);
}
/// <summary>A page of the items of an export job.</summary>
public sealed record ExportItemQuery
{
public required long RunId { get; init; }
public ExportItemState? State { get; init; }
public long AfterId { get; init; }
public int Limit { get; init; } = 500;
}
/// <summary>Counts of the items of an export job.</summary>
public sealed record ExportRunSummary(int Total, IReadOnlyDictionary<ExportItemState, int> ByState);
+6
View File
@@ -30,6 +30,12 @@ public interface IFebeStorage : IAsyncDisposable
IImportStore Imports { get; }
IExportStore Exports { get; }
IVideoAnalysisStore VideoAnalyses { get; }
IMediaConversionStore Conversions { get; }
ISettingsStore Settings { get; }
IDatabaseMaintenance Maintenance { get; }
@@ -0,0 +1,33 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// Converted files added to entries by the conversion for the library (spec §4.10, §8.3 <c>media_conversion</c>).
/// Only records: no method touches a file.
/// </summary>
public interface IMediaConversionStore
{
/// <summary>
/// Records a conversion. <see cref="DuplicateRecordException"/> when the file already has a current (Pending,
/// Converted or Failed) conversion in that format.
/// </summary>
Task<MediaConversion> AddAsync(MediaConversion conversion, CancellationToken ct = default);
/// <summary>
/// Writes state, path, bytes, SHA-256, times and error. <see cref="KeyNotFoundException"/> for a missing id;
/// <see cref="DuplicateRecordException"/> when the new state collides with another current conversion (as in <see cref="AddAsync"/>).
/// </summary>
Task UpdateAsync(MediaConversion conversion, CancellationToken ct = default);
Task<MediaConversion?> GetAsync(long id, CancellationToken ct = default);
/// <summary>The conversions of one library file, in creation order.</summary>
Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default);
/// <summary>Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate).</summary>
Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default);
/// <summary>The queue of the conversion, in order, by key.</summary>
Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default);
}
@@ -0,0 +1,19 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// Outcomes of «È un video fermo?» by SHA-256 of the video and number of the algorithm (spec §4.10, §8.3
/// <c>video_analysis</c>). No link to the library: an outcome outlives deletion and re-import of the same file.
/// </summary>
public interface IVideoAnalysisStore
{
/// <summary>The analysis with the highest algorithm number for this SHA-256, or null.</summary>
Task<VideoAnalysis?> GetAsync(string sha256, CancellationToken ct = default);
/// <summary>The analysis with the highest algorithm number for each SHA-256 that has one, keyed by lower-case SHA-256.</summary>
Task<IReadOnlyDictionary<string, VideoAnalysis>> GetManyAsync(IReadOnlyCollection<string> sha256s, CancellationToken ct = default);
/// <summary>Stores (or replaces) the outcome of one algorithm for one SHA-256.</summary>
Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default);
}
+9
View File
@@ -40,6 +40,9 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
Events = new EventStore(this);
Following = new FollowingStore(this);
Imports = new ImportStore(this);
Exports = new ExportStore(this);
VideoAnalyses = new VideoAnalysisStore(this);
Conversions = new MediaConversionStore(this);
Settings = new SettingsStore(this);
}
@@ -67,6 +70,12 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
public IImportStore Imports { get; }
public IExportStore Exports { get; }
public IVideoAnalysisStore VideoAnalyses { get; }
public IMediaConversionStore Conversions { get; }
public ISettingsStore Settings { get; }
public IDatabaseMaintenance Maintenance => this;
@@ -0,0 +1,246 @@
-- 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 path that touches
-- the new tables is AccountStore.DeleteAsync, which disables the account's destinations and keeps its user name on them
-- before deleting the account (nothing to do while there are no destinations); 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»): the store never writes NULL, and re-links an orphan row when its file is
-- adopted again or its destination is attached to the account again.
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
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 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;
-- 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';
+14 -1
View File
@@ -467,7 +467,20 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
ct);
public Task DeleteAsync(long accountId, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery(), ct);
db.WriteAsync(
w =>
{
// Its export destinations stay, disabled (spec §4.10): «Automatica» goes off and forgets «Solo i nuovi», so
// attaching the folder again never restarts it without asking; they keep the user name, then ON DELETE SET
// NULL clears the link. CHECKs of export_destination make the delete fail if either is not written first.
w.Command("""
UPDATE export_destination SET removed_account_username = (SELECT username FROM account WHERE id = @id),
automatic = 0, automatic_since = NULL
WHERE account_id = @id
""").With("@id", accountId).ExecuteNonQuery();
w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery();
},
ct);
private static Account? ReadOne(SqliteCommand command)
{
+789
View File
@@ -0,0 +1,789 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class ExportStore(FebeDatabase db) : IExportStore
{
private const string DestinationColumns =
"id, scope, account_id, removed_account_username, label, root_path, content_types, photo_format, video_format, naming_scheme, "
+ "highlight_naming_scheme, profile_naming_scheme, automatic, automatic_since, paused_at, last_error, created_at, removed_at";
private const string CopyColumns =
"id, destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state, superseded_by_sha256, origin, "
+ "relative_path, bytes, copy_sha256, copied_at, state_changed_at, last_error";
private const string RunColumns = "id, destination_id, kind, origin, state, started_at, completed_at, last_error";
private const string ItemColumns =
"id, run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state, note, relative_path, copy_id, last_error";
/// <summary>The frame instant as the identity indexes see it: <c>ifnull(frame_at_ms, -1)</c>.</summary>
private const string IdentityWhere =
"destination_id = @d AND source_sha256 = @h AND account_id = @a AND variant = @v AND format = @f AND ifnull(frame_at_ms, -1) = @fr";
// The lookups, also read by the plan tests (ExportConstraintTests.ExportLookupsUseTheirIndex).
internal const string CurrentCopySql = $"SELECT {CopyColumns} FROM export_copy WHERE {IdentityWhere} AND state IN ('Copied', 'Failed') LIMIT 1";
internal const string LatestCopySql = $"SELECT {CopyColumns} FROM export_copy WHERE {IdentityWhere} ORDER BY id DESC LIMIT 1";
internal const string CopiesBySha256Sql = $"SELECT {CopyColumns} FROM export_copy WHERE source_sha256 = @h OR superseded_by_sha256 = @h ORDER BY id DESC";
internal const string CopyByPathSql =
$"SELECT {CopyColumns} FROM export_copy WHERE destination_id = @d AND relative_path = @p AND state IN ('Copied', 'Superseded') LIMIT 1";
internal const string CountCopiesSql = "SELECT state, COUNT(*) FROM export_copy WHERE destination_id = @d GROUP BY state";
internal const string UnfinishedRunsSql = $"SELECT {RunColumns} FROM export_run WHERE state IN ('Running', 'Interrupted', 'Paused')";
/// <summary>
/// Copies of a destination by key (@d, @after, @limit; @s with a state). <c>+state</c> keeps the planner on
/// ix_export_copy_destination_id, which reads in key order, instead of sorting the copies of that state at each page.
/// </summary>
internal static string CopiesOfDestinationSql(bool withState) =>
$"SELECT {CopyColumns} FROM export_copy WHERE destination_id = @d{(withState ? " AND +state = @s" : string.Empty)} AND id > @after ORDER BY id LIMIT @limit";
/// <summary>Items of a job by key (@r, @after, @limit; @s with a state).</summary>
internal static string ItemsOfRunSql(bool withState) =>
$"SELECT {ItemColumns} FROM export_item WHERE run_id = @r{(withState ? " AND state = @s" : string.Empty)} AND id > @after ORDER BY id LIMIT @limit";
// Mapping --------------------------------------------------------------------------------------------------------
private static ExportDestination ReadDestination(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
Scope = r.GetEnum<ExportScope>(1),
AccountId = r.GetInt64OrNull(2),
RemovedAccountUsername = r.GetTextOrNull(3),
Label = r.GetTextOrNull(4),
RootPath = r.GetString(5),
ContentTypes = (ContentTypes)r.GetInt32(6),
PhotoFormat = r.GetEnumOrNull<ExportFormat>(7),
VideoFormat = r.GetEnumOrNull<ExportFormat>(8),
NamingScheme = r.GetTextOrNull(9),
HighlightNamingScheme = r.GetTextOrNull(10),
ProfileNamingScheme = r.GetTextOrNull(11),
Automatic = r.GetBool(12),
AutomaticSince = r.GetTimeOrNull(13),
PausedAt = r.GetTimeOrNull(14),
LastError = r.GetTextOrNull(15),
CreatedAt = r.GetTime(16),
RemovedAt = r.GetTimeOrNull(17),
};
private static ExportCopy ReadCopy(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
DestinationId = r.GetInt64(1),
AccountId = r.GetInt64OrNull(2),
MediaId = r.GetInt64OrNull(3),
SourceSha256 = r.GetString(4),
Variant = r.GetEnum<ExportVariant>(5),
Format = r.GetEnum<ExportFormat>(6),
FrameAt = r.GetDurationOrNull(7),
State = r.GetEnum<ExportCopyState>(8),
SupersededBySha256 = r.GetTextOrNull(9),
Origin = r.GetEnum<ExportCopyOrigin>(10),
RelativePath = r.GetTextOrNull(11),
Bytes = r.GetInt64OrNull(12),
CopySha256 = r.GetTextOrNull(13),
CopiedAt = r.GetTime(14),
StateChangedAt = r.GetTimeOrNull(15),
LastError = r.GetTextOrNull(16),
};
private static ExportRun ReadRun(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
DestinationId = r.GetInt64(1),
Kind = r.GetEnum<ExportRunKind>(2),
Origin = r.GetEnum<ExportRunOrigin>(3),
State = r.GetEnum<ExportRunState>(4),
StartedAt = r.GetTime(5),
CompletedAt = r.GetTimeOrNull(6),
LastError = r.GetTextOrNull(7),
};
private static ExportItem ReadItem(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
RunId = r.GetInt64(1),
MediaId = r.GetInt64OrNull(2),
AccountId = r.GetInt64OrNull(3),
SourceSha256 = r.GetTextOrNull(4),
Variant = r.GetEnum<ExportVariant>(5),
Format = r.GetEnum<ExportFormat>(6),
FrameAt = r.GetDurationOrNull(7),
State = r.GetEnum<ExportItemState>(8),
Note = r.GetTextOrNull(9),
RelativePath = r.GetTextOrNull(10),
CopyId = r.GetInt64OrNull(11),
LastError = r.GetTextOrNull(12),
};
private static List<T> ReadAll<T>(SqliteCommand command, Func<SqliteDataReader, T> read)
{
using var r = command.ExecuteReader();
var list = new List<T>();
while (r.Read())
{
list.Add(read(r));
}
return list;
}
private static T? ReadFirst<T>(SqliteCommand command, Func<SqliteDataReader, T> read)
where T : class
{
using var r = command.ExecuteReader();
return r.Read() ? read(r) : null;
}
private static void BindDestinationSettings(SqliteCommand c, ExportDestination d) =>
c.With("@label", Sql.Text(d.Label))
.With("@content_types", (long)d.ContentTypes)
.With("@photo_format", Sql.Enum(d.PhotoFormat))
.With("@video_format", Sql.Enum(d.VideoFormat))
.With("@naming_scheme", Sql.Text(d.NamingScheme))
.With("@highlight_naming_scheme", Sql.Text(d.HighlightNamingScheme))
.With("@profile_naming_scheme", Sql.Text(d.ProfileNamingScheme))
.With("@automatic", Sql.Bool(d.Automatic))
.With("@automatic_since", Sql.Time(d.AutomaticSince))
.With("@paused_at", Sql.Time(d.PausedAt))
.With("@last_error", Sql.Text(d.LastError));
private static void BindCopyState(SqliteCommand c, ExportCopy copy) =>
c.With("@media_id", Sql.Int(copy.MediaId))
.With("@state", Sql.Enum(copy.State))
.With("@superseded_by", Sql.Text(ExportValues.OptionalSha(copy.SupersededBySha256, nameof(copy.SupersededBySha256))))
.With("@origin", Sql.Enum(copy.Origin))
.With("@relative_path", Sql.Text(ExportValues.OptionalPath(copy.RelativePath)))
.With("@bytes", Sql.Int(copy.Bytes))
.With("@copy_sha256", Sql.Text(ExportValues.OptionalSha(copy.CopySha256, nameof(copy.CopySha256))))
.With("@copied_at", Sql.Time(copy.CopiedAt))
.With("@state_changed_at", Sql.Time(copy.StateChangedAt))
.With("@last_error", Sql.Text(copy.LastError));
private static SqliteCommand BindIdentity(SqliteCommand c, ExportCopyIdentity identity) =>
c.With("@d", identity.DestinationId)
.With("@h", ExportValues.Sha(identity.SourceSha256, nameof(identity.SourceSha256)))
.With("@a", identity.AccountId)
.With("@v", Sql.Enum(identity.Variant))
.With("@f", Sql.Enum(identity.Format))
.With("@fr", ExportValues.FrameKey(identity.FrameAt));
private static string CopyCollision(ExportCopy copy) =>
$"Nella destinazione {copy.DestinationId} c'è già una copia corrente dello stesso file per lo stesso account, variante e formato, "
+ "oppure una copia registrata sullo stesso percorso.";
private static void BindRun(SqliteCommand c, ExportRun run) =>
c.With("@destination_id", run.DestinationId)
.With("@kind", Sql.Enum(run.Kind))
.With("@origin", Sql.Enum(run.Origin))
.With("@state", Sql.Enum(run.State))
.With("@started_at", Sql.Time(run.StartedAt))
.With("@completed_at", Sql.Time(run.CompletedAt))
.With("@last_error", Sql.Text(run.LastError));
private static void BindItem(SqliteCommand c, ExportItem item) =>
c.With("@run_id", item.RunId)
.With("@media_id", Sql.Int(item.MediaId))
.With("@account_id", Sql.Int(item.AccountId))
.With("@source_sha256", Sql.Text(ExportValues.OptionalSha(item.SourceSha256, nameof(item.SourceSha256))))
.With("@variant", Sql.Enum(item.Variant))
.With("@format", Sql.Enum(item.Format))
.With("@frame_at_ms", Sql.Duration(item.FrameAt))
.With("@state", Sql.Enum(item.State))
.With("@note", Sql.Text(item.Note))
.With("@relative_path", Sql.Text(ExportValues.OptionalPath(item.RelativePath)))
.With("@copy_id", Sql.Int(item.CopyId))
.With("@last_error", Sql.Text(item.LastError));
/// <summary>
/// Runs a write guarded by a unique index of 0003 and reports a collision as <see cref="DuplicateRecordException"/>,
/// as the other stores do, so the callers in Febe.Core can catch it without knowing SQLite.
/// </summary>
private static T Unique<T>(Func<T> write, string message)
{
try
{
return write();
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException(message, ex);
}
}
private static void ValidateSettings(ExportDestination d)
{
if (d.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo))
{
throw new ArgumentException($"{photo} non è un formato per le foto.", nameof(d));
}
if (d.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video))
{
throw new ArgumentException($"{video} non è un formato per i video.", nameof(d));
}
if (!d.Automatic && d.AutomaticSince is not null)
{
throw new ArgumentException("«Solo i nuovi» vale solo con «Automatica» accesa.", nameof(d));
}
}
// Destinations ---------------------------------------------------------------------------------------------------
public Task<ExportDestination> AddDestinationAsync(ExportDestination destination, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentException.ThrowIfNullOrWhiteSpace(destination.RootPath);
if (destination.RemovedAt is not null || destination.RemovedAccountUsername is not null)
{
throw new ArgumentException("Una destinazione nuova non può essere già ritirata né senza account.", nameof(destination));
}
if ((destination.Scope == ExportScope.General) != (destination.AccountId is null))
{
throw new ArgumentException("La cartella generale non ha account; la cartella di un account sì.", nameof(destination));
}
ValidateSettings(destination);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO export_destination (scope, account_id, label, root_path, content_types, photo_format, video_format,
naming_scheme, highlight_naming_scheme, profile_naming_scheme, automatic, automatic_since, paused_at, last_error, created_at)
VALUES (@scope, @account_id, @label, @root_path, @content_types, @photo_format, @video_format,
@naming_scheme, @highlight_naming_scheme, @profile_naming_scheme, @automatic, @automatic_since, @paused_at, @last_error, @created_at)
""");
BindDestinationSettings(c, destination);
c.With("@scope", Sql.Enum(destination.Scope))
.With("@account_id", Sql.Int(destination.AccountId))
.With("@root_path", destination.RootPath)
.With("@created_at", Sql.Time(destination.CreatedAt));
Unique(
c.ExecuteNonQuery,
destination.Scope == ExportScope.General
? "C'è già una cartella generale in uso: va tolta prima di sceglierne un'altra."
: $"L'account {destination.AccountId} ha già una cartella propria in uso: va tolta prima di sceglierne un'altra.");
return destination with { Id = w.LastInsertRowId() };
},
ct);
}
public Task UpdateDestinationAsync(ExportDestination destination, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(destination);
ValidateSettings(destination);
return db.WriteAsync(
w =>
{
var stored = ReadFirst(w.Command($"SELECT {DestinationColumns} FROM export_destination WHERE id = @id").With("@id", destination.Id), ReadDestination)
?? throw new KeyNotFoundException($"Destinazione di esportazione {destination.Id} non trovata.");
if (stored.IsRetired)
{
throw new ArgumentException($"La destinazione {destination.Id} è ritirata: non si modifica più.", nameof(destination));
}
if (stored.IsOrphan && destination.Automatic)
{
throw new ArgumentException(
$"La destinazione {destination.Id} è di un account rimosso: «Automatica» si accende solo dopo averla ridata a un account.",
nameof(destination));
}
if (stored.Scope != destination.Scope || stored.AccountId != destination.AccountId
|| !string.Equals(stored.RootPath, destination.RootPath, StringComparison.Ordinal))
{
throw new ArgumentException(
$"Ambito, account e cartella della destinazione {destination.Id} non cambiano: un'altra cartella è una destinazione nuova.",
nameof(destination));
}
var c = w.Command("""
UPDATE export_destination SET label = @label, content_types = @content_types, photo_format = @photo_format,
video_format = @video_format, naming_scheme = @naming_scheme, highlight_naming_scheme = @highlight_naming_scheme,
profile_naming_scheme = @profile_naming_scheme, automatic = @automatic, automatic_since = @automatic_since,
paused_at = @paused_at, last_error = @last_error
WHERE id = @id
""");
BindDestinationSettings(c, destination);
c.With("@id", destination.Id).ExecuteNonQuery();
},
ct);
}
public Task<ExportDestination?> GetDestinationAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {DestinationColumns} FROM export_destination WHERE id = @id").With("@id", id), ReadDestination), ct);
public Task<ExportDestination?> GetGeneralDestinationAsync(CancellationToken ct = default) =>
db.ReadAsync(
c => ReadFirst(c.Command($"SELECT {DestinationColumns} FROM export_destination WHERE scope = 'General' AND removed_at IS NULL"), ReadDestination),
ct);
public Task<ExportDestination?> GetAccountDestinationAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c => ReadFirst(
c.Command($"SELECT {DestinationColumns} FROM export_destination WHERE account_id = @a AND removed_at IS NULL").With("@a", accountId),
ReadDestination),
ct);
public Task<IReadOnlyList<ExportDestination>> ListDestinationsAsync(bool includeRetired = false, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportDestination>>(
c => ReadAll(
c.Command($"""
SELECT {DestinationColumns} FROM export_destination WHERE @all = 1 OR removed_at IS NULL
ORDER BY CASE scope WHEN 'General' THEN 0 ELSE 1 END, id
""").With("@all", Sql.Bool(includeRetired)),
ReadDestination),
ct);
public Task RetireDestinationAsync(long id, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var changed = w.Command("""
UPDATE export_destination SET removed_at = @at, automatic = 0, automatic_since = NULL
WHERE id = @id AND removed_at IS NULL
""").With("@at", Sql.Time(at)).With("@id", id).ExecuteNonQuery();
if (changed == 0 && w.Command("SELECT COUNT(*) FROM export_destination WHERE id = @id").With("@id", id).ScalarInt64() == 0)
{
throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
}
},
ct);
public Task AttachDestinationAsync(long id, long accountId, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var stored = ReadFirst(w.Command($"SELECT {DestinationColumns} FROM export_destination WHERE id = @id").With("@id", id), ReadDestination)
?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
if (!stored.IsOrphan || stored.IsRetired)
{
throw new InvalidOperationException($"La destinazione {id} non è la cartella in uso di un account rimosso.");
}
if (w.Command("SELECT COUNT(*) FROM export_destination WHERE account_id = @a AND removed_at IS NULL").With("@a", accountId).ScalarInt64() > 0)
{
throw new InvalidOperationException($"L'account {accountId} ha già una cartella propria in uso.");
}
w.Command("UPDATE export_destination SET account_id = @a, removed_account_username = NULL WHERE id = @id")
.With("@a", accountId).With("@id", id).ExecuteNonQuery();
// «Automatica» stays off (the removal of the account turned it off): turning it on again asks «Solo i nuovi».
Unique(
w.Command("UPDATE export_copy SET account_id = @a WHERE destination_id = @id AND account_id IS NULL")
.With("@a", accountId).With("@id", id).ExecuteNonQuery,
$"L'account {accountId} ha già una copia corrente uguale a una copia della destinazione {id}.");
},
ct);
// «Esporta questo account» ---------------------------------------------------------------------------------------
public Task<bool?> GetAccountExportEnabledAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
using var r = c.Command("SELECT enabled FROM export_account WHERE account_id = @a").With("@a", accountId).ExecuteReader();
return r.Read() ? r.GetBool(0) : (bool?)null;
},
ct);
public Task SetAccountExportEnabledAsync(long accountId, bool enabled, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("""
INSERT INTO export_account (account_id, enabled) VALUES (@a, @e)
ON CONFLICT (account_id) DO UPDATE SET enabled = excluded.enabled
""").With("@a", accountId).With("@e", Sql.Bool(enabled)).ExecuteNonQuery(),
ct);
// Copies ---------------------------------------------------------------------------------------------------------
public Task<ExportCopy> AddCopyAsync(ExportCopy copy, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(copy);
if (copy.AccountId is null)
{
throw new ArgumentException("Una copia si registra sempre con il suo account effettivo.", nameof(copy));
}
ExportValues.ValidateShape(copy.Variant, copy.Format, copy.FrameAt);
var source = ExportValues.Sha(copy.SourceSha256, nameof(copy.SourceSha256));
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state,
superseded_by_sha256, origin, relative_path, bytes, copy_sha256, copied_at, state_changed_at, last_error)
VALUES (@destination_id, @account_id, @media_id, @source_sha256, @variant, @format, @frame_at_ms, @state,
@superseded_by, @origin, @relative_path, @bytes, @copy_sha256, @copied_at, @state_changed_at, @last_error)
""");
BindCopyState(c, copy);
c.With("@destination_id", copy.DestinationId)
.With("@account_id", copy.AccountId.Value)
.With("@source_sha256", source)
.With("@variant", Sql.Enum(copy.Variant))
.With("@format", Sql.Enum(copy.Format))
.With("@frame_at_ms", Sql.Duration(copy.FrameAt));
Unique(c.ExecuteNonQuery, CopyCollision(copy));
var id = w.LastInsertRowId();
return ReadFirst(w.Command($"SELECT {CopyColumns} FROM export_copy WHERE id = @id").With("@id", id), ReadCopy)!;
},
ct);
}
public Task UpdateCopyAsync(ExportCopy copy, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(copy);
var source = ExportValues.Sha(copy.SourceSha256, nameof(copy.SourceSha256));
return db.WriteAsync(
w =>
{
var stored = ReadFirst(w.Command($"SELECT {CopyColumns} FROM export_copy WHERE id = @id").With("@id", copy.Id), ReadCopy)
?? throw new KeyNotFoundException($"Copia {copy.Id} non trovata.");
if (stored.DestinationId != copy.DestinationId || stored.AccountId != copy.AccountId
|| !string.Equals(stored.SourceSha256, source, StringComparison.Ordinal) || stored.Variant != copy.Variant
|| stored.Format != copy.Format || ExportValues.FrameKey(stored.FrameAt) != ExportValues.FrameKey(copy.FrameAt))
{
throw new ArgumentException(
$"L'identità della copia {copy.Id} non cambia: «Copia di nuovo» aggiunge una riga.", nameof(copy));
}
var c = w.Command("""
UPDATE export_copy SET media_id = @media_id, state = @state, superseded_by_sha256 = @superseded_by, origin = @origin,
relative_path = @relative_path, bytes = @bytes, copy_sha256 = @copy_sha256, copied_at = @copied_at,
state_changed_at = @state_changed_at, last_error = @last_error
WHERE id = @id
""");
BindCopyState(c, copy);
c.With("@id", copy.Id);
Unique(c.ExecuteNonQuery, CopyCollision(copy));
},
ct);
}
public Task<ExportCopy?> GetCopyAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {CopyColumns} FROM export_copy WHERE id = @id").With("@id", id), ReadCopy), ct);
public Task<ExportCopy?> FindCurrentCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(identity);
return db.ReadAsync(
c => ReadFirst(
BindIdentity(c.Command(CurrentCopySql), identity),
ReadCopy),
ct);
}
public Task<ExportCopy?> FindLatestCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(identity);
return db.ReadAsync(
c => ReadFirst(BindIdentity(c.Command(LatestCopySql), identity), ReadCopy),
ct);
}
public Task<IReadOnlyList<ExportCopy>> ListCopiesBySha256Async(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync<IReadOnlyList<ExportCopy>>(
c => ReadAll(
c.Command(CopiesBySha256Sql).With("@h", sha),
ReadCopy),
ct);
}
public Task<ExportCopy?> FindCopyByPathAsync(long destinationId, string relativePath, CancellationToken ct = default)
{
var path = ExportValues.Path(relativePath);
return db.ReadAsync(
c => ReadFirst(
c.Command(CopyByPathSql).With("@d", destinationId).With("@p", path),
ReadCopy),
ct);
}
public Task<IReadOnlyList<ExportCopy>> ListCopiesAsync(long destinationId, ExportCopyState? state = null, long afterId = 0, int limit = 500, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportCopy>>(
c =>
{
var command = c.Command(CopiesOfDestinationSql(state is not null))
.With("@d", destinationId).With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 10_000));
if (state is { } s)
{
command.With("@s", Sql.Enum(s));
}
return ReadAll(command, ReadCopy);
},
ct);
public Task<IReadOnlyDictionary<ExportCopyState, int>> CountCopiesAsync(long destinationId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<ExportCopyState, int>>(
c =>
{
var counts = Enum.GetValues<ExportCopyState>().ToDictionary(s => s, _ => 0);
using var r = c.Command(CountCopiesSql).With("@d", destinationId).ExecuteReader();
while (r.Read())
{
counts[r.GetEnum<ExportCopyState>(0)] = r.GetInt32(1);
}
return counts;
},
ct);
public Task<ExportCopy> RelinkOrphanCopyAsync(long copyId, long accountId, long? mediaId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var select = $"SELECT {CopyColumns} FROM export_copy WHERE id = @id";
var stored = ReadFirst(w.Command(select).With("@id", copyId), ReadCopy)
?? throw new KeyNotFoundException($"Copia {copyId} non trovata.");
if (stored.AccountId is not null)
{
throw new InvalidOperationException($"La copia {copyId} ha già il suo account.");
}
Unique(
w.Command("UPDATE export_copy SET account_id = @a, media_id = coalesce(@m, media_id), state_changed_at = @at WHERE id = @id")
.With("@a", accountId).With("@m", Sql.Int(mediaId)).With("@at", Sql.Time(at)).With("@id", copyId).ExecuteNonQuery,
$"L'account {accountId} ha già una copia corrente uguale alla copia {copyId}.");
return ReadFirst(w.Command(select).With("@id", copyId), ReadCopy)!;
},
ct);
public Task<int> SupersedeCopiesAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default)
{
var old = ExportValues.Sha(oldSha256, nameof(oldSha256));
var replacement = ExportValues.Sha(newSha256, nameof(newSha256));
if (string.Equals(old, replacement, StringComparison.Ordinal))
{
throw new ArgumentException("Il file nuovo ha lo stesso SHA-256 di quello vecchio.", nameof(newSha256));
}
return db.WriteAsync(
w =>
{
// The library file goes back to an earlier one (A→B→A: «Tieni il più grande» is not transitive, and a rebuild
// keeps the file on disk): its copies match the library again. The newest Superseded row of each identity
// becomes Copied again, unless a current row of that identity exists (copied again meanwhile, or failed):
// then it stays Superseded by the old file, as history. Removed rows only lose the stamp.
var revived = w.Command("""
UPDATE export_copy SET state = 'Copied', superseded_by_sha256 = NULL, state_changed_at = @at
WHERE id IN (
SELECT max(s.id) FROM export_copy s
WHERE s.account_id = @a AND s.superseded_by_sha256 = @old AND s.source_sha256 = @new AND s.state = 'Superseded'
AND NOT EXISTS (
SELECT 1 FROM export_copy c
WHERE c.destination_id = s.destination_id AND c.source_sha256 = s.source_sha256 AND c.account_id = s.account_id
AND c.variant = s.variant AND c.format = s.format AND ifnull(c.frame_at_ms, -1) = ifnull(s.frame_at_ms, -1)
AND c.state IN ('Copied', 'Failed'))
GROUP BY s.destination_id, s.variant, s.format, ifnull(s.frame_at_ms, -1))
""").With("@a", accountId).With("@old", old).With("@new", replacement).With("@at", Sql.Time(at)).ExecuteNonQuery();
var unstamped = w.Command("""
UPDATE export_copy SET superseded_by_sha256 = NULL
WHERE account_id = @a AND superseded_by_sha256 = @old AND source_sha256 = @new AND state = 'Removed'
""").With("@a", accountId).With("@old", old).With("@new", replacement).ExecuteNonQuery();
// Rows superseded by the old file move to the new one first, so the rows changed below are not counted twice.
var moved = w.Command("""
UPDATE export_copy SET superseded_by_sha256 = @new
WHERE account_id = @a AND superseded_by_sha256 = @old AND source_sha256 <> @new
""").With("@a", accountId).With("@old", old).With("@new", replacement).ExecuteNonQuery();
var superseded = w.Command("""
UPDATE export_copy SET state = 'Superseded', superseded_by_sha256 = @new, state_changed_at = @at
WHERE account_id = @a AND source_sha256 = @old AND state = 'Copied'
""").With("@a", accountId).With("@old", old).With("@new", replacement).With("@at", Sql.Time(at)).ExecuteNonQuery();
var stamped = w.Command("""
UPDATE export_copy SET superseded_by_sha256 = @new
WHERE account_id = @a AND source_sha256 = @old AND state = 'Removed'
AND (superseded_by_sha256 IS NULL OR superseded_by_sha256 <> @new)
""").With("@a", accountId).With("@old", old).With("@new", replacement).ExecuteNonQuery();
return revived + unstamped + moved + superseded + stamped;
},
ct);
}
// Jobs and their files -------------------------------------------------------------------------------------------
public Task<ExportRun> CreateRunAsync(ExportRun run, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(run);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO export_run (destination_id, kind, origin, state, started_at, completed_at, last_error)
VALUES (@destination_id, @kind, @origin, @state, @started_at, @completed_at, @last_error)
""");
BindRun(c, run);
c.ExecuteNonQuery();
return run with { Id = w.LastInsertRowId() };
},
ct);
}
public Task UpdateRunAsync(ExportRun run, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(run);
return db.WriteAsync(
w =>
{
var c = w.Command("""
UPDATE export_run SET destination_id = @destination_id, kind = @kind, origin = @origin, state = @state,
started_at = @started_at, completed_at = @completed_at, last_error = @last_error
WHERE id = @id
""");
BindRun(c, run);
if (c.With("@id", run.Id).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Esportazione {run.Id} non trovata.");
}
},
ct);
}
public Task<ExportRun?> GetRunAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {RunColumns} FROM export_run WHERE id = @id").With("@id", runId), ReadRun), ct);
public Task<IReadOnlyList<ExportRun>> ListRunsAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(c => ReadAll(c.Command($"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC"), ReadRun), ct);
public Task<IReadOnlyList<ExportRun>> ListUnfinishedRunsAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(
c =>
{
// Read through the partial index; the handful of unfinished runs is ordered here, not by a sort in SQLite.
var runs = ReadAll(c.Command(UnfinishedRunsSql), ReadRun);
runs.Sort((a, b) => a.Id.CompareTo(b.Id));
return runs;
},
ct);
public Task AddItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(items);
foreach (var item in items)
{
ArgumentNullException.ThrowIfNull(item, nameof(items));
if (item.AccountId is null)
{
throw new ArgumentException("Un file da esportare si aggiunge sempre con il suo account effettivo.", nameof(items));
}
// NULLs are distinct in ux_export_item_file: an item without its file could be added twice on resume.
if (item.MediaId is null)
{
throw new ArgumentException("Un file da esportare si aggiunge sempre con il suo file della libreria.", nameof(items));
}
ExportValues.ValidateShape(item.Variant, item.Format, item.FrameAt);
}
return db.WriteAsync(
w =>
{
foreach (var item in items)
{
var c = w.Command("""
INSERT INTO export_item (run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state, note,
relative_path, copy_id, last_error)
VALUES (@run_id, @media_id, @account_id, @source_sha256, @variant, @format, @frame_at_ms, @state, @note,
@relative_path, @copy_id, @last_error)
ON CONFLICT DO NOTHING
""");
BindItem(c, item);
c.ExecuteNonQuery();
}
},
ct);
}
public Task UpdateItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(items);
return db.WriteAsync(
w =>
{
foreach (var item in items)
{
// Job, file and request (variant, format, frame) are the identity of the item in ux_export_item_file:
// they are never rewritten, and the file is cleared only by its deletion (ON DELETE SET NULL).
var c = w.Command("""
UPDATE export_item SET account_id = coalesce(@account_id, account_id), source_sha256 = @source_sha256,
state = @state, note = @note, relative_path = @relative_path, copy_id = @copy_id, last_error = @last_error
WHERE id = @id AND run_id = @run_id AND variant = @variant AND format = @format
AND ifnull(frame_at_ms, -1) = @frame_key AND (media_id IS NULL OR media_id = @media_id)
""");
BindItem(c, item);
if (c.With("@id", item.Id).With("@frame_key", ExportValues.FrameKey(item.FrameAt)).ExecuteNonQuery() == 0)
{
if (w.Command("SELECT COUNT(*) FROM export_item WHERE id = @id AND run_id = @r").With("@id", item.Id).With("@r", item.RunId).ScalarInt64() == 0)
{
throw new KeyNotFoundException($"File di esportazione {item.Id} non trovato.");
}
throw new ArgumentException(
$"Il file, la variante, il formato e l'istante del file di esportazione {item.Id} non cambiano.", nameof(items));
}
}
},
ct);
}
public Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {ItemColumns} FROM export_item WHERE id = @id").With("@id", itemId), ReadItem), ct);
public Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(query);
return db.ReadAsync<IReadOnlyList<ExportItem>>(
c =>
{
var command = c.Command(ItemsOfRunSql(query.State is not null))
.With("@r", query.RunId).With("@after", query.AfterId).With("@limit", (long)Math.Clamp(query.Limit, 1, 10_000));
if (query.State is { } state)
{
command.With("@s", Sql.Enum(state));
}
return ReadAll(command, ReadItem);
},
ct);
}
public Task<ExportRunSummary> GetRunSummaryAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var byState = Enum.GetValues<ExportItemState>().ToDictionary(s => s, _ => 0);
var total = 0;
using var r = c.Command("SELECT state, COUNT(*) FROM export_item WHERE run_id = @r GROUP BY state").With("@r", runId).ExecuteReader();
while (r.Read())
{
var count = r.GetInt32(1);
byState[r.GetEnum<ExportItemState>(0)] = count;
total += count;
}
return new ExportRunSummary(total, byState);
},
ct);
public Task DeleteRunAsync(long runId, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
// Items go by cascade; copies and files in the destination are never touched here.
w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery();
},
ct);
}
+54
View File
@@ -0,0 +1,54 @@
using System.Text;
using Febe.Core.Domain;
namespace Febe.Data.Stores;
/// <summary>Checks and normal forms shared by the export and conversion stores. The CHECKs of 0003 stay as the last line of defence.</summary>
internal static class ExportValues
{
/// <summary>A SHA-256 as 64 hex characters, stored lower case.</summary>
public static string Sha(string? value, string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value, name);
var text = value.Trim();
if (text.Length != 64 || !text.All(char.IsAsciiHexDigit))
{
throw new ArgumentException("Uno SHA-256 è fatto di 64 cifre esadecimali.", name);
}
return text.ToLowerInvariant();
}
public static string? OptionalSha(string? value, string name) => value is null ? null : Sha(value, name);
/// <summary>
/// A path relative to a destination root: '/' separated and NFC, so the same name is always the same text
/// (export_copy.relative_path also compares ASCII letters without case).
/// </summary>
public static string Path(string? value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value);
return value.Replace('\\', '/').Normalize(NormalizationForm.FormC);
}
public static string? OptionalPath(string? value) => value is null ? null : Path(value);
/// <summary>The frame instant as the identity indexes see it: milliseconds, or -1 for no frame.</summary>
public static long FrameKey(TimeSpan? frameAt) => frameAt is { } f ? (long)f.TotalMilliseconds : -1;
/// <summary>The pairs of variant and format the schema accepts: Whole with Original, Converted with another format, Frame with a picture at an instant.</summary>
public static void ValidateShape(ExportVariant variant, ExportFormat format, TimeSpan? frameAt)
{
var valid = variant switch
{
ExportVariant.Whole => format == ExportFormat.Original && frameAt is null,
ExportVariant.Converted => format != ExportFormat.Original && frameAt is null,
ExportVariant.Frame => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless && frameAt is { } f && f >= TimeSpan.Zero,
_ => false,
};
if (!valid)
{
throw new ArgumentException($"Variante {variant} e formato {format} non vanno insieme{(frameAt is null ? string.Empty : " con un istante")}.", nameof(variant));
}
}
}
@@ -0,0 +1,151 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
{
private const string Columns =
"id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error";
/// <summary>The queue of the conversion by key (@after, @limit), also read by the plan tests.</summary>
internal const string PendingSql = $"SELECT {Columns} FROM media_conversion WHERE state = 'Pending' AND id > @after ORDER BY id LIMIT @limit";
private static MediaConversion Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
MediaId = r.GetInt64(1),
Format = r.GetEnum<ExportFormat>(2),
State = r.GetEnum<MediaConversionState>(3),
SourceSha256 = r.GetString(4),
RelativePath = r.GetTextOrNull(5),
Bytes = r.GetInt64OrNull(6),
Sha256 = r.GetTextOrNull(7),
CreatedAt = r.GetTime(8),
ConvertedAt = r.GetTimeOrNull(9),
StateChangedAt = r.GetTimeOrNull(10),
LastError = r.GetTextOrNull(11),
};
private static List<MediaConversion> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<MediaConversion>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
private static void Validate(MediaConversion conversion)
{
ArgumentNullException.ThrowIfNull(conversion);
if (conversion.Format == ExportFormat.Original)
{
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(conversion));
}
if (conversion.State is not (MediaConversionState.Pending or MediaConversionState.Failed)
&& (conversion.RelativePath is null || conversion.Bytes is null || conversion.Sha256 is null || conversion.ConvertedAt is null))
{
throw new ArgumentException("Un file convertito ha percorso, byte, SHA-256 e data della conversione.", nameof(conversion));
}
}
// The path is relative to the account folder and written as given, like media.relative_path.
private static void Bind(SqliteCommand c, MediaConversion conversion) =>
c.With("@media_id", conversion.MediaId)
.With("@format", Sql.Enum(conversion.Format))
.With("@state", Sql.Enum(conversion.State))
.With("@source_sha256", ExportValues.Sha(conversion.SourceSha256, nameof(conversion.SourceSha256)))
.With("@relative_path", Sql.Text(conversion.RelativePath))
.With("@bytes", Sql.Int(conversion.Bytes))
.With("@sha256", Sql.Text(ExportValues.OptionalSha(conversion.Sha256, nameof(conversion.Sha256))))
.With("@created_at", Sql.Time(conversion.CreatedAt))
.With("@converted_at", Sql.Time(conversion.ConvertedAt))
.With("@state_changed_at", Sql.Time(conversion.StateChangedAt))
.With("@last_error", Sql.Text(conversion.LastError));
/// <summary>Runs a write guarded by ux_media_conversion_current; a collision is a <see cref="DuplicateRecordException"/>.</summary>
private static int Execute(SqliteCommand command, MediaConversion conversion)
{
try
{
return command.ExecuteNonQuery();
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException(
$"Il file {conversion.MediaId} ha già una conversione in {conversion.Format} in coda, fatta o non riuscita.", ex);
}
}
public Task<MediaConversion> AddAsync(MediaConversion conversion, CancellationToken ct = default)
{
Validate(conversion);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at,
state_changed_at, last_error)
VALUES (@media_id, @format, @state, @source_sha256, @relative_path, @bytes, @sha256, @created_at, @converted_at,
@state_changed_at, @last_error)
""");
Bind(c, conversion);
Execute(c, conversion);
var id = w.LastInsertRowId();
using var r = w.Command($"SELECT {Columns} FROM media_conversion WHERE id = @id").With("@id", id).ExecuteReader();
r.Read();
return Read(r);
},
ct);
}
public Task UpdateAsync(MediaConversion conversion, CancellationToken ct = default)
{
Validate(conversion);
return db.WriteAsync(
w =>
{
// The original and the format are the identity of a conversion: they are never rewritten.
var c = w.Command("""
UPDATE media_conversion SET state = @state, source_sha256 = @source_sha256, relative_path = @relative_path, bytes = @bytes,
sha256 = @sha256, created_at = @created_at, converted_at = @converted_at, state_changed_at = @state_changed_at,
last_error = @last_error
WHERE id = @id AND media_id = @media_id AND format = @format
""");
Bind(c, conversion);
if (Execute(c.With("@id", conversion.Id), conversion) == 0)
{
throw new KeyNotFoundException($"Conversione {conversion.Id} del file {conversion.MediaId} in {conversion.Format} non trovata.");
}
},
ct);
}
public Task<MediaConversion?> GetAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE id = @id").With("@id", id)).FirstOrDefault(), ct);
public Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<MediaConversion>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE media_id = @m ORDER BY id").With("@m", mediaId)),
ct);
public Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE sha256 = @h ORDER BY id").With("@h", sha)),
ct);
}
public Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<MediaConversion>>(
c => ReadAll(c.Command(PendingSql)
.With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 10_000))),
ct);
}
@@ -0,0 +1,69 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore
{
private const int KeysPerQuery = 500;
private static VideoAnalysis Read(SqliteDataReader r) =>
new(r.GetString(0), r.GetInt32(1), r.GetEnum<VideoAnalysisOutcome>(2), r.GetTime(3));
public Task<VideoAnalysis?> GetAsync(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync(
c =>
{
using var r = c.Command("""
SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 = @h ORDER BY algorithm DESC LIMIT 1
""").With("@h", sha).ExecuteReader();
return r.Read() ? Read(r) : null;
},
ct);
}
public Task<IReadOnlyDictionary<string, VideoAnalysis>> GetManyAsync(IReadOnlyCollection<string> sha256s, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(sha256s);
var keys = sha256s.Select(s => ExportValues.Sha(s, nameof(sha256s))).Distinct(StringComparer.Ordinal).ToList();
return db.ReadAsync<IReadOnlyDictionary<string, VideoAnalysis>>(
c =>
{
var result = new Dictionary<string, VideoAnalysis>(StringComparer.Ordinal);
foreach (var chunk in keys.Chunk(KeysPerQuery))
{
using var command = c.Command(string.Empty);
command.CommandText = $"SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 IN ({command.AddList("h", chunk)})";
using var r = command.ExecuteReader();
while (r.Read())
{
var analysis = Read(r);
if (!result.TryGetValue(analysis.Sha256, out var known) || known.Algorithm < analysis.Algorithm)
{
result[analysis.Sha256] = analysis;
}
}
}
return result;
},
ct);
}
public Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(analysis);
var sha = ExportValues.Sha(analysis.Sha256, nameof(analysis));
ArgumentOutOfRangeException.ThrowIfLessThan(analysis.Algorithm, 1, nameof(analysis));
return db.WriteAsync(
w => w.Command("""
INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at) VALUES (@h, @alg, @o, @at)
ON CONFLICT (sha256, algorithm) DO UPDATE SET outcome = excluded.outcome, analyzed_at = excluded.analyzed_at
""").With("@h", sha).With("@alg", (long)analysis.Algorithm).With("@o", Sql.Enum(analysis.Outcome)).With("@at", Sql.Time(analysis.AnalyzedAt))
.ExecuteNonQuery(),
ct);
}
}
@@ -0,0 +1,603 @@
using Febe.Core.Domain;
using Febe.Data;
using Febe.Data.Stores;
using Febe.Tests.Support;
using Microsoft.Data.Sqlite;
using static Febe.Tests.Data.ExportWorld;
namespace Febe.Tests.Data;
/// <summary>The constraints of migration 0003 (spec §4.10, §8.3), written with raw SQL so the CHECKs answer alone.</summary>
[TestClass]
public sealed class ExportConstraintTests
{
private static readonly string[] ExportTables =
["export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion"];
private static readonly string Sha63 = Make.Sha(1)[1..];
private static readonly string Sha65 = Make.Sha(1) + "0";
[TestMethod]
public async Task UnknownValuesAreRejectedInEveryTable()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var run = await InsertAsync(db, "export_run", w.RunRow());
await InsertAsync(db, "export_item", w.ItemRow(run));
await InsertAsync(db, "export_account", new Dictionary<string, object?> { ["account_id"] = w.Luca, ["enabled"] = 1L });
await InsertAsync(db, "video_analysis", AnalysisRow());
await InsertAsync(db, "media_conversion", w.ConversionRow());
await InsertAsync(db, "export_copy", w.CopyRow());
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Tutti")), "ambito sconosciuto");
await RejectedAsync(db, "export_destination", DestinationRow(("photo_format", "Mp4")), "formato video per le foto");
await RejectedAsync(db, "export_destination", DestinationRow(("video_format", "Jpg")), "formato foto per i video");
await RejectedAsync(db, "export_destination", DestinationRow(("content_types", -1L)), "tipi negativi");
await RejectedAsync(db, "export_account", new Dictionary<string, object?> { ["account_id"] = w.Marta, ["enabled"] = 2L }, "interruttore non booleano");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Gone"), ("relative_path", "x/1.jpg")), "stato della copia");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Intero"), ("relative_path", "x/2.jpg")), "variante");
await RejectedAsync(db, "export_copy", w.CopyRow(("format", "Gif"), ("variant", "Converted"), ("copy_sha256", Make.Sha(2)), ("relative_path", "x/3.jpg")), "formato");
await RejectedAsync(db, "export_copy", w.CopyRow(("origin", "Copied"), ("account_id", w.Luca), ("media_id", w.LucaMedia), ("relative_path", "x/4.jpg")), "origine");
await RejectedAsync(db, "export_run", w.RunRow(("kind", "Export")), "tipo di lavoro");
await RejectedAsync(db, "export_run", w.RunRow(("origin", "Auto")), "origine del lavoro");
await RejectedAsync(db, "export_run", w.RunRow(("state", "Done")), "stato del lavoro");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("state", "Done"), ("media_id", w.LucaMedia)), "stato del file");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Intero"), ("media_id", w.LucaMedia)), "variante del file");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Gif"), ("variant", "Converted"), ("media_id", w.LucaMedia)), "formato del file");
await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Fermo"), ("sha256", Make.Sha(6))), "esito");
await RejectedAsync(db, "video_analysis", AnalysisRow(("algorithm", 0L), ("sha256", Make.Sha(6))), "algoritmo 0");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("format", "Original"), ("media_id", w.LucaMedia)), "un convertito ha un altro formato");
await RejectedAsync(
db,
"media_conversion",
w.ConversionRow(("state", "Done"), ("media_id", w.LucaMedia), ("relative_path", "taggati/a.jpg.jpg"), ("bytes", 1L), ("sha256", Make.Sha(2)), ("converted_at", 0L)),
"stato della conversione");
}
[TestMethod]
public async Task Sha256MustHave64Characters()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var run = await InsertAsync(db, "export_run", w.RunRow());
foreach (var bad in new[] { Sha63, Sha65 })
{
await RejectedAsync(db, "export_copy", w.CopyRow(("source_sha256", bad), ("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)), "source_sha256");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg"), ("copy_sha256", bad)), "copy_sha256");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", bad)), "superseded_by_sha256");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("source_sha256", bad)), "export_item.source_sha256");
await RejectedAsync(db, "video_analysis", AnalysisRow(("sha256", bad)), "video_analysis.sha256");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("source_sha256", bad)), "media_conversion.source_sha256");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("sha256", bad)), "media_conversion.sha256");
}
}
[TestMethod]
public async Task VariantAndFormatGoTogether()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var run = await InsertAsync(db, "export_run", w.RunRow());
await RejectedAsync(db, "export_copy", w.CopyRow(("format", "Jpg")), "intero in JPG");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("copy_sha256", Make.Sha(2))), "convertito in Originale");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Mp4"), ("frame_at_ms", 0L), ("copy_sha256", Make.Sha(2))), "fotogramma in MP4");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2))), "fotogramma senza istante");
await RejectedAsync(db, "export_copy", w.CopyRow(("frame_at_ms", 0L)), "intero con un istante");
await RejectedAsync(db, "export_copy", w.CopyRow(("copy_sha256", Make.Sha(2))), "intero con uno SHA-256 diverso dall'originale");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg")), "convertito uguale all'originale: è un intero");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Jpg")), "file intero in JPG");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "Png")), "file fotogramma senza istante");
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2)), ("relative_path", "marta.demo/a.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Png"), ("frame_at_ms", 1000L), ("copy_sha256", Make.Sha(3)), ("relative_path", "marta.demo/a_t0m01s000.png")));
await InsertAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "WebpLossless"), ("frame_at_ms", 0L)));
}
[TestMethod]
public async Task EveryStateButFailedHadAFile()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", null)), "copiato senza percorso");
await RejectedAsync(db, "export_copy", w.CopyRow(("bytes", null)), "copiato senza byte");
await RejectedAsync(db, "export_copy", w.CopyRow(("copy_sha256", null)), "copiato senza SHA-256 della copia");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("relative_path", null)), "tolto senza percorso");
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", "")), "percorso vuoto");
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)));
}
[TestMethod]
public async Task SupersededNeedsTheFileThatTookItsPlace()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Superseded")), "superato senza il file nuovo");
await RejectedAsync(db, "export_copy", w.CopyRow(("superseded_by_sha256", Make.Sha(9))), "copiato con il file nuovo");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("superseded_by_sha256", Make.Sha(9))), "non riuscito con il file nuovo");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Superseded"), ("superseded_by_sha256", Make.Sha(1)), ("relative_path", "marta.demo/c.jpg")), "superata dal suo stesso originale");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", Make.Sha(1))), "tolta e segnata con il suo stesso originale");
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", Make.Sha(9))));
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Superseded"), ("superseded_by_sha256", Make.Sha(9)), ("relative_path", "marta.demo/b.jpg")));
}
[TestMethod]
public async Task OneCurrentConversionPerFileAndFormat()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var first = await InsertAsync(db, "media_conversion", w.ConversionRow());
await RejectedAsync(db, "media_conversion", w.ConversionRow(), "due conversioni in JPG in coda per lo stesso file");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("state", "Failed")), "una non riuscita accanto a una in coda");
await RejectedAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2)), "una fatta accanto a una in coda");
await InsertAsync(db, "media_conversion", w.ConversionRow(("format", "Png")));
await InsertAsync(db, "media_conversion", w.ConversionRow(("media_id", w.LucaMedia)));
await ExecuteAsync(db, "UPDATE media_conversion SET state = 'Removed', relative_path = 'post/a.jpg.jpg', bytes = 1, sha256 = @h, converted_at = 0 WHERE id = @id", ("@id", first), ("@h", Make.Sha(2)));
var second = await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(3)));
await ExecuteAsync(db, "UPDATE media_conversion SET state = 'Superseded' WHERE id = @id", ("@id", second));
await InsertAsync(db, "media_conversion", w.ConversionRow());
await RejectedAsync(db, "media_conversion", Converted(w, "WebpLossless", Make.Sha(1)), "un convertito uguale al suo originale");
await InsertAsync(db, "media_conversion", Converted(w, "WebpLossless", Make.Sha(4)));
}
private static Dictionary<string, object?> Converted(ExportWorld w, string format, string sha256) =>
w.ConversionRow(("format", format), ("state", "Converted"), ("relative_path", $"post/a.jpg.{format}"), ("bytes", 1L), ("sha256", sha256), ("converted_at", 0L));
[TestMethod]
public async Task DestinationsKeepTheirRules()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await RejectedAsync(db, "export_destination", DestinationRow(("removed_at", null)), "una seconda cartella generale in uso");
await RejectedAsync(db, "export_destination", DestinationRow(("account_id", w.Marta)), "la cartella generale non ha account");
await RejectedAsync(db, "export_destination", DestinationRow(("removed_account_username", "marta.demo")), "la cartella generale non ha nome d'account");
await RejectedAsync(db, "export_destination", DestinationRow(("root_path", null)), "senza cartella");
await RejectedAsync(db, "export_destination", DestinationRow(("root_path", "")), "cartella vuota");
await RejectedAsync(db, "export_destination", DestinationRow(("content_types", null)), "senza tipi");
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Account"), ("account_id", w.Marta), ("removed_at", null)), "una seconda cartella in uso per un account");
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Account")), "una cartella d'account senza account né nome");
await RejectedAsync(db, "export_destination", DestinationRow(("removed_at", null), ("scope", "Account"), ("account_id", w.Luca), ("automatic_since", 5L)), "«Solo i nuovi» senza «Automatica»");
await RejectedAsync(db, "export_destination", DestinationRow(("automatic", 1L)), "una destinazione ritirata non è automatica");
await ExecuteAsync(db, "UPDATE export_destination SET removed_at = 1 WHERE id = @id", ("@id", w.General));
await InsertAsync(db, "export_destination", DestinationRow(("removed_at", null)));
await ExecuteAsync(db, "UPDATE export_destination SET removed_at = 1 WHERE id = @id", ("@id", w.Own));
await InsertAsync(db, "export_destination", DestinationRow(("scope", "Account"), ("account_id", w.Marta), ("removed_at", null), ("automatic", 1L), ("automatic_since", 5L)));
(string, object?)[] orphan = [("scope", "Account"), ("removed_account_username", "vecchio.demo"), ("removed_at", null)];
await RejectedAsync(db, "export_destination", DestinationRow([.. orphan, ("automatic", 1L)]), "una cartella senza il suo account non è automatica");
await InsertAsync(db, "export_destination", DestinationRow(orphan));
}
[TestMethod]
public async Task OneCurrentCopyPerIdentity()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var first = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/1.jpg")));
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/2.jpg")), "la stessa identità copiata due volte");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)), "non riuscita accanto a una copiata");
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Removed' WHERE id = @id", ("@id", first));
var second = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/2.jpg")));
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Superseded', superseded_by_sha256 = @h WHERE id = @id", ("@id", second), ("@h", Make.Sha(9)));
await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/3.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("media_id", w.LucaMedia), ("relative_path", "luca.demo/1.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Png"), ("copy_sha256", Make.Sha(2)), ("relative_path", "marta.demo/1.png")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 0L), ("copy_sha256", Make.Sha(3)), ("relative_path", "marta.demo/f0.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 1000L), ("copy_sha256", Make.Sha(4)), ("relative_path", "marta.demo/f1.jpg")));
}
[TestMethod]
public async Task APathIsNeverRecordedTwice()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var first = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/x.jpg")));
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "marta.demo/x.jpg")), "due copie sullo stesso file");
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "Marta.Demo/X.JPG")), "lo stesso file su Windows, maiuscole diverse");
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("state", "Superseded"), ("superseded_by_sha256", Make.Sha(9)), ("relative_path", "marta.demo/x.jpg")), "superata sullo stesso file");
await InsertAsync(db, "export_copy", w.CopyRow(("destination_id", w.Own), ("relative_path", "marta.demo/x.jpg")));
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Removed' WHERE id = @id", ("@id", first));
await InsertAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "marta.demo/x.jpg")));
}
[TestMethod]
public async Task RecordsCannotBeDeletedFromUnderTheirCopies()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await InsertAsync(db, "export_copy", w.CopyRow());
await InsertAsync(db, "export_run", w.RunRow(("destination_id", w.Own)));
var conversion = await InsertAsync(db, "media_conversion", w.ConversionRow());
var withCopy = await Assert.ThrowsExactlyAsync<SqliteException>(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.General)));
Assert.AreEqual(19, withCopy.SqliteErrorCode, "una destinazione con copie si ritira, non si cancella");
var withRun = await Assert.ThrowsExactlyAsync<SqliteException>(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.Own)));
Assert.AreEqual(19, withRun.SqliteErrorCode, "una destinazione con lavori si ritira, non si cancella");
var entry = await Assert.ThrowsExactlyAsync<SqliteException>(() => db.Entries.RemoveAsync(w.MartaEntry));
Assert.AreEqual(19, entry.SqliteErrorCode, "un file con un convertito registrato non si cancella");
Assert.IsNotNull(await db.Entries.GetAsync(w.MartaEntry));
Assert.IsNotNull(await db.Media.GetAsync(w.MartaMedia));
Assert.IsNotNull(await db.Conversions.GetAsync(conversion));
var account = await Assert.ThrowsExactlyAsync<SqliteException>(() => db.Accounts.DeleteAsync(w.Marta));
Assert.AreEqual(19, account.SqliteErrorCode, "anche attraverso la rimozione dell'account");
Assert.IsNotNull(await db.Accounts.GetAsync(w.Marta));
Assert.IsNotNull(await db.Conversions.GetAsync(conversion));
}
[TestMethod]
public async Task EntryRemovalKeepsCopiesBySha256()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 });
await db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1) }]);
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0));
await db.Entries.RemoveAsync(w.MartaEntry);
var kept = await db.Exports.GetCopyAsync(copy.Id);
Assert.IsNotNull(kept);
Assert.IsNull(kept.MediaId);
Assert.AreEqual(Make.Sha(1), kept.SourceSha256);
Assert.AreEqual(w.Marta, kept.AccountId);
Assert.Contains(kept, await db.Exports.ListCopiesBySha256Async(Make.Sha(1)));
var item = (await db.Exports.ListItemsAsync(new() { RunId = run.Id })).Single();
Assert.IsNull(item.MediaId);
Assert.AreEqual(Make.Sha(1), item.SourceSha256);
Assert.IsNotNull(await db.VideoAnalyses.GetAsync(Make.Sha(1)));
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
}
[TestMethod]
public async Task AccountRemovalKeepsItsDestination()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
var current = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Marta, @"H:\Marta") with { Automatic = true, AutomaticSince = Make.T0.AddDays(2) });
await db.Exports.SetAccountExportEnabledAsync(w.Marta, true);
var martaCopy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var lucaCopy = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
await db.Accounts.DeleteAsync(w.Marta);
await db.Accounts.DeleteAsync(w.Luca);
foreach (var id in new[] { w.Own, current.Id })
{
var destination = (await db.Exports.GetDestinationAsync(id))!;
Assert.IsNull(destination.AccountId);
Assert.AreEqual("marta.demo", destination.RemovedAccountUsername);
Assert.IsTrue(destination.IsOrphan);
}
var disabled = (await db.Exports.GetDestinationAsync(current.Id))!;
Assert.IsNull(disabled.RemovedAt, "la cartella in uso resta in uso, senza account");
Assert.IsFalse(disabled.Automatic, "rimuovere l'account la disattiva");
Assert.IsNull(disabled.AutomaticSince, "e dimentica «Solo i nuovi»");
Assert.IsFalse((await db.Exports.ListDestinationsAsync()).Any(d => d.Automatic));
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
Assert.AreEqual(0L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_account"));
var general = (await db.Exports.GetGeneralDestinationAsync())!;
Assert.AreEqual(w.General, general.Id);
Assert.IsNull(general.AccountId);
Assert.IsNull(general.RemovedAccountUsername);
// Two orphan copies with the same identity but for the account (now NULL): both kept.
var copies = await db.Exports.ListCopiesBySha256Async(Make.Sha(1));
CollectionAssert.AreEquivalent(new[] { martaCopy.Id, lucaCopy.Id }, copies.Select(c => c.Id).ToArray());
Assert.IsTrue(copies.All(c => c.AccountId is null && c.MediaId is null && c.Identity is null));
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
}
[TestMethod]
public async Task RawAccountDeleteWithoutUserNameFails()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var error = await Assert.ThrowsExactlyAsync<SqliteException>(() => ExecuteAsync(db, "DELETE FROM account WHERE id = @id", ("@id", w.Marta)));
Assert.AreEqual(19, error.SqliteErrorCode, "il CHECK vale anche sull'azione SET NULL");
Assert.IsNotNull(await db.Accounts.GetAsync(w.Marta));
Assert.AreEqual(w.Marta, (await db.Exports.GetDestinationAsync(w.Own))!.AccountId);
}
[TestMethod]
public async Task RemovedAccountComesBack()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var ownCopy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
var generalCopy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
await db.Exports.UpdateDestinationAsync((await db.Exports.GetDestinationAsync(w.Own))! with { Automatic = true, AutomaticSince = Make.T0.AddDays(1) });
await db.Accounts.DeleteAsync(w.Marta);
var orphan = (await db.Exports.GetDestinationAsync(w.Own))!;
Assert.IsFalse(orphan.Automatic, "rimuovere l'account la disattiva");
Assert.IsNull(orphan.AutomaticSince);
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(orphan with { Automatic = true }), "senza account non si accende");
var again = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
await db.Exports.AttachDestinationAsync(w.Own, again.Id);
var own = (await db.Exports.GetDestinationAsync(w.Own))!;
Assert.AreEqual(again.Id, own.AccountId);
Assert.IsNull(own.RemovedAccountUsername);
Assert.IsFalse(own.Automatic, "ridata all'account, «Automatica» resta spenta: riaccenderla chiede di nuovo");
Assert.IsNull(own.AutomaticSince, "il vecchio «Solo i nuovi» non torna");
await db.Exports.UpdateDestinationAsync(own with { Automatic = true, AutomaticSince = Make.T0.AddDays(3) });
Assert.AreEqual(Make.T0.AddDays(3), (await db.Exports.GetDestinationAsync(w.Own))!.AutomaticSince);
Assert.AreEqual(own.Id, (await db.Exports.GetAccountDestinationAsync(again.Id))!.Id);
Assert.AreEqual(again.Id, (await db.Exports.GetCopyAsync(ownCopy.Id))!.AccountId);
Assert.IsNull((await db.Exports.GetCopyAsync(generalCopy.Id))!.AccountId, "le copie di altre destinazioni restano orfane finché non si adottano");
var relinked = await db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0.AddDays(2));
Assert.AreEqual(again.Id, relinked.AccountId);
Assert.AreEqual(Make.T0.AddDays(2), relinked.StateChangedAt);
Assert.AreEqual(generalCopy.Id, (await db.Exports.FindCopyByPathAsync(w.General, "marta.demo/a.jpg"))!.Id);
Assert.AreEqual(1L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE destination_id = @d AND relative_path = 'marta.demo/a.jpg'", ("@d", w.General)));
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => db.Exports.AttachDestinationAsync(w.Own, again.Id));
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => db.Exports.AttachDestinationAsync(w.General, again.Id));
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.RelinkOrphanCopyAsync(9999, again.Id, null, Make.T0));
}
[TestMethod]
public async Task DestinationRetirementKeepsRecords()
{
using var temp = new TempFolder();
var root = temp.Combine("copie");
Directory.CreateDirectory(Path.Combine(root, "marta.demo"));
var file = Path.Combine(root, "marta.demo", "a.jpg");
await File.WriteAllBytesAsync(file, [1, 2, 3]);
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db, root);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0, State = ExportRunState.Completed });
await db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), State = ExportItemState.Copied, CopyId = copy.Id }]);
await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1));
Assert.IsNull(await db.Exports.GetGeneralDestinationAsync());
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetDestinationAsync(w.General))!.RemovedAt);
Assert.IsNotNull(await db.Exports.GetCopyAsync(copy.Id));
Assert.IsNotNull(await db.Exports.GetRunAsync(run.Id));
Assert.HasCount(1, await db.Exports.ListItemsAsync(new() { RunId = run.Id }));
Assert.IsTrue(File.Exists(file), "togliere una destinazione non tocca i file già copiati");
var next = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, temp.Combine("altre")));
Assert.AreEqual(next.Id, (await db.Exports.GetGeneralDestinationAsync())!.Id);
}
/// <summary>
/// Every foreign key of the new tables has an index usable for <c>child = ?</c>: the plan of that lookup is a SEARCH,
/// never a SCAN (an index merely starting with the column is not enough when it is partial on another condition).
/// </summary>
[TestMethod]
public async Task ExportForeignKeysHaveAnIndex()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var checkedKeys = 0;
foreach (var table in ExportTables)
{
var columns = await db.ReadAsync(
c =>
{
using var r = c.Command($"SELECT \"from\" FROM pragma_foreign_key_list('{table}')").ExecuteReader();
var list = new List<string>();
while (r.Read())
{
list.Add(r.GetString(0));
}
return list;
},
default);
foreach (var column in columns)
{
var plan = await PlanAsync(db, $"SELECT 1 FROM {table} WHERE {column} = 1");
Assert.Contains("SEARCH", plan, $"{table}.{column}: {plan}");
Assert.DoesNotContain("SCAN", plan, $"{table}.{column}: {plan}");
checkedKeys++;
}
}
Assert.AreEqual(11, checkedKeys, "le chiavi esterne delle tabelle nuove");
}
/// <summary>
/// The lookups of the stores read their index, with and without ANALYZE statistics: a SEARCH, no SCAN and no
/// temporary B-tree (but the ORDER BY of the handful of rows of a SHA-256). Index names only where the choice is the point.
/// </summary>
[TestMethod]
public async Task ExportLookupsUseTheirIndex()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await FillAsync(db, w);
// Without statistics the planner's choice is the point for the «Copie» set shape and the latest row of an identity.
var setShape = await PlanAsync(
db,
"""
SELECT m.entry_id FROM export_copy c JOIN media m ON m.sha256 = c.source_sha256
JOIN entry x ON x.id = m.entry_id AND x.account_id = c.account_id
WHERE c.destination_id = @d AND c.state = 'Copied'
""",
("@d", w.General));
Assert.Contains("USING COVERING INDEX ix_export_copy_destination (destination_id=? AND state=?)", setShape, setShape);
var latest = await PlanAsync(db, ExportStore.LatestCopySql, Identity(w));
Assert.Contains("ix_export_copy_sha256", latest, latest);
Assert.DoesNotContain("TEMP B-TREE", latest, latest);
await CheckLookupsAsync(db, w, "senza ANALYZE");
await db.WriteAsync(x => x.Command("ANALYZE").ExecuteNonQuery(), default);
await CheckLookupsAsync(db, w, "con ANALYZE");
}
private static async Task CheckLookupsAsync(FebeDatabase db, ExportWorld w, string when)
{
var run = await ScalarAsync(db, "SELECT MIN(id) FROM export_run");
var lookups = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
{
("FindCurrentCopyAsync", ExportStore.CurrentCopySql, Identity(w), false),
("FindLatestCopyAsync", ExportStore.LatestCopySql, Identity(w), false),
("FindCopyByPathAsync", ExportStore.CopyByPathSql, [("@d", w.General), ("@p", "marta.demo/17.jpg")], false),
("ListCopiesBySha256Async", ExportStore.CopiesBySha256Sql, [("@h", Make.Sha(17))], true),
("ListCopiesAsync", ExportStore.CopiesOfDestinationSql(false), [("@d", w.General), ("@after", 0L), ("@limit", 500L)], false),
("ListCopiesAsync (stato)", ExportStore.CopiesOfDestinationSql(true), [("@d", w.General), ("@s", "Copied"), ("@after", 0L), ("@limit", 500L)], false),
("CountCopiesAsync", ExportStore.CountCopiesSql, [("@d", w.General)], false),
("ListUnfinishedRunsAsync", ExportStore.UnfinishedRunsSql, [], false),
("ListItemsAsync", ExportStore.ItemsOfRunSql(false), [("@r", run), ("@after", 0L), ("@limit", 500L)], false),
("ListItemsAsync (stato)", ExportStore.ItemsOfRunSql(true), [("@r", run), ("@s", "Pending"), ("@after", 0L), ("@limit", 500L)], false),
("ListPendingAsync", MediaConversionStore.PendingSql, [("@after", 0L), ("@limit", 500L)], false),
};
var problems = new List<string>();
foreach (var (name, sql, parameters, sortAllowed) in lookups)
{
var plan = await PlanAsync(db, sql, parameters);
var withoutAllowedSort = sortAllowed ? plan.Replace("USE TEMP B-TREE FOR ORDER BY", string.Empty, StringComparison.Ordinal) : plan;
if (!plan.Contains("SEARCH", StringComparison.Ordinal) || plan.Contains("SCAN", StringComparison.Ordinal)
|| withoutAllowedSort.Contains("TEMP B-TREE", StringComparison.Ordinal))
{
problems.Add($"{name}: {plan}");
}
}
Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}");
}
private static (string, object?)[] Identity(ExportWorld w) =>
[("@d", w.General), ("@h", Make.Sha(17)), ("@a", w.Marta), ("@v", "Whole"), ("@f", "Original"), ("@fr", -1L)];
/// <summary>About 1,000 copies over three destinations and two accounts, three jobs with their items, 300 finished jobs, and a queue of conversions.</summary>
private static Task FillAsync(FebeDatabase db, ExportWorld w) =>
db.WriteAsync(
x =>
{
var destinations = new[] { w.General, w.Own, InsertDestination(x, w.Luca) };
var copied = x.Command("""
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, superseded_by_sha256,
relative_path, bytes, copy_sha256, copied_at)
VALUES (@d, @a, @h, 'Whole', 'Original', @s, @by, @p, 10, @h, 0)
""");
var failed = x.Command("""
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, copied_at)
VALUES (@d, @a, @h, 'Whole', 'Original', 'Failed', 0)
""");
for (var i = 0; i < 1000; i++)
{
var destination = destinations[i % 3];
var account = i % 2 == 0 ? w.Marta : w.Luca;
var state = (i % 10) switch { 7 => "Removed", 8 => "Superseded", _ => "Copied" };
if (i % 10 == 9)
{
failed.With("@d", destination).With("@a", account).With("@h", Make.Sha(i)).ExecuteNonQuery();
continue;
}
copied.With("@d", destination).With("@a", account).With("@h", Make.Sha(i)).With("@s", state)
.With("@by", state == "Superseded" ? Make.Sha(5000 + i) : null)
.With("@p", $"{(account == w.Marta ? "marta.demo" : "luca.demo")}/{i}.jpg").ExecuteNonQuery();
}
var run = x.Command("INSERT INTO export_run (destination_id, kind, origin, state, started_at) VALUES (@d, 'Copy', 'Manual', @s, 0)");
var item = x.Command("""
INSERT INTO export_item (run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state)
VALUES (@r, NULL, @a, @h, 'Frame', 'Jpg', @f, @s)
""");
foreach (var state in new[] { "Completed", "Running", "Interrupted" })
{
run.With("@d", w.General).With("@s", state).ExecuteNonQuery();
var runId = x.LastInsertRowId();
for (var i = 0; i < 200; i++)
{
item.With("@r", runId).With("@a", w.Marta).With("@h", Make.Sha(i)).With("@f", (long)i * 1000).With("@s", i % 3 == 0 ? "Pending" : "Copied").ExecuteNonQuery();
}
}
// The finished jobs of months of use: the unfinished ones are a handful among many.
for (var i = 0; i < 300; i++)
{
run.With("@d", w.General).With("@s", i % 5 == 0 ? "Cancelled" : "Completed").ExecuteNonQuery();
}
var entry = x.Command("INSERT INTO entry (account_id, kind, published_at, state, provenance, discovered_at) VALUES (@a, 'Post', 0, 'Downloaded', 'Imported', 0)");
var media = x.Command("INSERT INTO media (entry_id, position, kind, state, sha256) VALUES (@e, 1, 'Photo', 'Imported', @h)");
var conversion = x.Command("INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) VALUES (@m, @f, @s, @h, 0)");
for (var i = 0; i < 100; i++)
{
entry.With("@a", w.Marta).ExecuteNonQuery();
media.With("@e", x.LastInsertRowId()).With("@h", Make.Sha(9000 + i)).ExecuteNonQuery();
var mediaId = x.LastInsertRowId();
foreach (var format in new[] { "Jpg", "Png" })
{
conversion.With("@m", mediaId).With("@f", format).With("@s", i % 4 == 0 ? "Pending" : "Failed").With("@h", Make.Sha(9000 + i)).ExecuteNonQuery();
}
}
},
default);
private static long InsertDestination(WriteContext x, long account)
{
x.Command("INSERT INTO export_destination (scope, account_id, root_path, content_types, created_at) VALUES ('Account', @a, 'K:/Luca', 63, 0)")
.With("@a", account).ExecuteNonQuery();
return x.LastInsertRowId();
}
private static Task<string> PlanAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
db.ReadAsync(
c =>
{
var command = c.Command("EXPLAIN QUERY PLAN " + sql);
foreach (var (name, value) in parameters)
{
command.With(name, value);
}
using var r = command.ExecuteReader();
var lines = new List<string>();
while (r.Read())
{
lines.Add(r.GetString(3));
}
return string.Join(" | ", lines);
},
default);
}
+507
View File
@@ -0,0 +1,507 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
using static Febe.Tests.Data.ExportWorld;
namespace Febe.Tests.Data;
/// <summary>Round trips of the export, still-video and conversion stores on a real database (times at ms, UTC).</summary>
[TestClass]
public sealed class ExportStoreTests
{
[TestMethod]
public async Task StorageExposesTheThreeStores()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
IFebeStorage storage = db;
Assert.IsNotNull(storage.Exports);
Assert.IsNotNull(storage.VideoAnalyses);
Assert.IsNotNull(storage.Conversions);
}
[TestMethod]
public async Task DestinationsRoundTrip()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var since = Make.T0.AddDays(3).AddMilliseconds(123);
var luca = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Luca, @"\\nas\copie\luca") with
{
Label = "Disco di rete",
ContentTypes = ContentTypes.PostPhotos | ContentTypes.Stories | ContentTypes.ProfilePicture,
PhotoFormat = ExportFormat.WebpLossless,
VideoFormat = ExportFormat.Mp4,
NamingScheme = "{anno}/{codice}",
HighlightNamingScheme = "{raccolta}/{numero}",
ProfileNamingScheme = "profilo/{data}",
Automatic = true,
AutomaticSince = since,
});
var read = (await db.Exports.GetDestinationAsync(luca.Id))!;
Assert.AreEqual(luca, read);
Assert.AreEqual(since, read.AutomaticSince);
Assert.AreEqual(luca.Id, (await db.Exports.GetAccountDestinationAsync(w.Luca))!.Id);
Assert.AreEqual(w.General, (await db.Exports.GetGeneralDestinationAsync())!.Id);
var general = (await db.Exports.GetDestinationAsync(w.General))!;
Assert.IsNull(general.PhotoFormat, "«Come le impostazioni generali»");
Assert.IsNull(general.NamingScheme, "«Come la libreria»");
Assert.IsFalse(general.Automatic, "«Automatica» spenta per impostazione predefinita");
var paused = read with { Automatic = false, AutomaticSince = null, PausedAt = Make.T0.AddDays(4), LastError = "Disco non raggiungibile", Label = null, VideoFormat = null };
await db.Exports.UpdateDestinationAsync(paused);
Assert.AreEqual(paused, await db.Exports.GetDestinationAsync(luca.Id));
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(5));
CollectionAssert.AreEqual(new[] { w.General, luca.Id }, (await db.Exports.ListDestinationsAsync()).Select(d => d.Id).ToArray());
CollectionAssert.AreEqual(new[] { w.General, w.Own, luca.Id }, (await db.Exports.ListDestinationsAsync(includeRetired: true)).Select(d => d.Id).ToArray());
Assert.IsNull(await db.Exports.GetAccountDestinationAsync(w.Marta));
}
[TestMethod]
public async Task DestinationsKeepTheirFolderScopeAndAccount()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var own = (await db.Exports.GetDestinationAsync(w.Own))!;
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateDestinationAsync(own with { Id = 9999 }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { RootPath = @"Z:\Altra" }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { AccountId = w.Luca }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { Scope = ExportScope.General, AccountId = null }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { PhotoFormat = ExportFormat.Mp4 }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { AutomaticSince = Make.T0 }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"Z:\a") with { RemovedAt = Make.T0 }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.Account, null, @"Z:\a")));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.General, w.Marta, @"Z:\a")));
await db.Exports.UpdateDestinationAsync(own with { Automatic = true });
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
var retired = (await db.Exports.GetDestinationAsync(w.Own))!;
Assert.IsTrue(retired.IsRetired);
Assert.IsFalse(retired.Automatic, "una destinazione ritirata non è più automatica");
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(retired));
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(9));
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetDestinationAsync(w.Own))!.RemovedAt, "ritirarla di nuovo non cambia nulla");
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.RetireDestinationAsync(9999, Make.T0));
}
[TestMethod]
public async Task TheAccountSwitchRoundTrips()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Marta), "nessuna scelta registrata");
await db.Exports.SetAccountExportEnabledAsync(w.Marta, true);
Assert.IsTrue(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
await db.Exports.SetAccountExportEnabledAsync(w.Marta, false);
Assert.IsFalse(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Luca));
}
[TestMethod]
public async Task CopiesRoundTripAndKeepTheirIdentity()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var frame = await db.Exports.AddCopyAsync(w.WholeCopy(@"marta.demo\2026\a_t0m01s500.png") with
{
Variant = ExportVariant.Frame,
Format = ExportFormat.Png,
FrameAt = TimeSpan.FromMilliseconds(1500),
CopySha256 = Make.Sha(2).ToUpperInvariant(),
Origin = ExportCopyOrigin.Adopted,
SourceSha256 = Make.Sha(1).ToUpperInvariant(),
});
var read = (await db.Exports.GetCopyAsync(frame.Id))!;
Assert.AreEqual(frame, read);
Assert.AreEqual("marta.demo/2026/a_t0m01s500.png", read.RelativePath, "separatore '/'");
Assert.AreEqual(Make.Sha(1), read.SourceSha256, "SHA-256 in minuscolo");
Assert.AreEqual(Make.Sha(2), read.CopySha256);
Assert.AreEqual(new ExportCopyIdentity(w.General, w.Marta, Make.Sha(1), ExportVariant.Frame, ExportFormat.Png, TimeSpan.FromMilliseconds(1500)), read.Identity);
var failed = read with { State = ExportCopyState.Failed, RelativePath = null, Bytes = null, CopySha256 = null, LastError = "Spazio esaurito", StateChangedAt = Make.T0.AddHours(2) };
await db.Exports.UpdateCopyAsync(failed);
Assert.AreEqual(failed, await db.Exports.GetCopyAsync(frame.Id));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddCopyAsync(w.WholeCopy("x.jpg") with { AccountId = null }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddCopyAsync(w.WholeCopy("x.jpg") with { SourceSha256 = "abc" }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddCopyAsync(w.WholeCopy("x.jpg") with { Format = ExportFormat.Jpg }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { AccountId = w.Luca }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { FrameAt = TimeSpan.Zero }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { Format = ExportFormat.Jpg }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { SourceSha256 = Make.Sha(3) }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { DestinationId = w.Own }));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateCopyAsync(failed with { Id = 9999 }));
}
[TestMethod]
public async Task CurrentAndLatestCopyOfAnIdentity()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var identity = new ExportCopyIdentity(w.General, w.Marta, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null);
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(identity));
Assert.IsNull(await db.Exports.FindLatestCopyAsync(identity));
var first = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
Assert.AreEqual(first.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
await db.Exports.UpdateCopyAsync(first with { State = ExportCopyState.Removed, StateChangedAt = Make.T0.AddDays(1) });
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(identity), "«Tolto» non è una copia corrente");
Assert.AreEqual(ExportCopyState.Removed, (await db.Exports.FindLatestCopyAsync(identity))!.State, "Tolto: mai accodato da solo");
var again = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg")); // «Copia di nuovo»
Assert.AreEqual(again.Id, (await db.Exports.FindLatestCopyAsync(identity))!.Id);
Assert.AreEqual(again.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
var frameZero = new ExportCopyIdentity(w.General, w.Marta, Make.Sha(1), ExportVariant.Frame, ExportFormat.Jpg, TimeSpan.Zero);
var atZero = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a_f0.jpg") with { Variant = ExportVariant.Frame, Format = ExportFormat.Jpg, FrameAt = TimeSpan.Zero, CopySha256 = Make.Sha(4) });
Assert.AreEqual(atZero.Id, (await db.Exports.FindCurrentCopyAsync(frameZero))!.Id);
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(frameZero with { FrameAt = null }), "nessun istante e l'istante 0 sono identità diverse");
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(identity with { AccountId = w.Luca }));
}
[TestMethod]
public async Task CopiesAreFoundBySha256AndByPath()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var general = await db.Exports.AddCopyAsync(w.WholeCopy("Marta.Demo/Caffè.jpg"));
var own = await db.Exports.AddCopyAsync(w.WholeCopy("caffè.jpg", destination: w.Own));
var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/caffè.jpg", account: w.Luca, media: w.LucaMedia));
await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/altro.jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2) });
CollectionAssert.AreEqual(new[] { luca.Id, own.Id, general.Id }, (await db.Exports.ListCopiesBySha256Async(Make.Sha(1).ToUpperInvariant())).Select(c => c.Id).ToArray());
Assert.AreEqual(general.Id, (await db.Exports.FindCopyByPathAsync(w.General, "marta.demo/CAFFÈ.JPG".Replace("È", "è", StringComparison.Ordinal)))!.Id, "maiuscole ASCII diverse");
Assert.AreEqual(general.Id, (await db.Exports.FindCopyByPathAsync(w.General, @"marta.demo\Caffe" + "\u0300" + ".jpg"))!.Id, "'\\' e forma NFD");
Assert.IsNull(await db.Exports.FindCopyByPathAsync(w.Own, "Marta.Demo/Caffè.jpg"));
await db.Exports.UpdateCopyAsync(general with { State = ExportCopyState.Removed });
Assert.IsNull(await db.Exports.FindCopyByPathAsync(w.General, "Marta.Demo/Caffè.jpg"), "un percorso «Tolto» è di nuovo libero");
}
[TestMethod]
public async Task CopiesOfADestinationArePagedAndCounted()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var ids = new List<long>();
for (var i = 0; i < 7; i++)
{
var copy = await db.Exports.AddCopyAsync(w.WholeCopy($"marta.demo/{i}.jpg") with { SourceSha256 = Make.Sha(100 + i), CopySha256 = Make.Sha(100 + i) });
ids.Add(copy.Id);
if (i % 3 == 0)
{
await db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed });
}
}
await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
var pages = new List<long>();
long after = 0;
while (true)
{
var page = await db.Exports.ListCopiesAsync(w.General, afterId: after, limit: 3);
if (page.Count == 0)
{
break;
}
pages.AddRange(page.Select(c => c.Id));
after = page[^1].Id;
}
CollectionAssert.AreEqual(ids, pages);
CollectionAssert.AreEqual(new[] { ids[0], ids[3], ids[6] }, (await db.Exports.ListCopiesAsync(w.General, ExportCopyState.Removed)).Select(c => c.Id).ToArray());
CollectionAssert.AreEqual(new[] { ids[4], ids[5] }, (await db.Exports.ListCopiesAsync(w.General, ExportCopyState.Copied, afterId: ids[3])).Select(c => c.Id).ToArray());
var counts = await db.Exports.CountCopiesAsync(w.General);
Assert.HasCount(Enum.GetValues<ExportCopyState>().Length, counts);
Assert.AreEqual(4, counts[ExportCopyState.Copied]);
Assert.AreEqual(3, counts[ExportCopyState.Removed]);
Assert.AreEqual(0, counts[ExportCopyState.Superseded]);
Assert.AreEqual(0, counts[ExportCopyState.Failed]);
}
[TestMethod]
public async Task SupersedingFollowsTheFileOfTheAccount()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var (a, b, c) = (Make.Sha(1), Make.Sha(2), Make.Sha(3));
var copied = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var removed = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own) with { State = ExportCopyState.Removed });
var converted = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.png") with { Variant = ExportVariant.Converted, Format = ExportFormat.Png, CopySha256 = Make.Sha(4) });
var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
Assert.AreEqual(3, await db.Exports.SupersedeCopiesAsync(w.Marta, a.ToUpperInvariant(), b, Make.T0.AddDays(1)));
var first = (await db.Exports.GetCopyAsync(copied.Id))!;
Assert.AreEqual(ExportCopyState.Superseded, first.State);
Assert.AreEqual(b, first.SupersededBySha256);
Assert.AreEqual(Make.T0.AddDays(1), first.StateChangedAt);
Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(converted.Id))!.State);
var stamped = (await db.Exports.GetCopyAsync(removed.Id))!;
Assert.AreEqual(ExportCopyState.Removed, stamped.State, "un «Tolto» resta tolto");
Assert.AreEqual(b, stamped.SupersededBySha256);
var other = (await db.Exports.GetCopyAsync(luca.Id))!;
Assert.AreEqual(ExportCopyState.Copied, other.State, "le copie di un altro account non cambiano");
Assert.IsNull(other.SupersededBySha256);
CollectionAssert.AreEquivalent(new[] { copied.Id, removed.Id, converted.Id }, (await db.Exports.ListCopiesBySha256Async(b)).Select(x => x.Id).ToArray());
Assert.AreEqual(3, await db.Exports.SupersedeCopiesAsync(w.Marta, b, c, Make.T0.AddDays(2)));
CollectionAssert.AreEquivalent(new[] { copied.Id, removed.Id, converted.Id }, (await db.Exports.ListCopiesBySha256Async(c)).Select(x => x.Id).ToArray());
Assert.IsEmpty(await db.Exports.ListCopiesBySha256Async(b));
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetCopyAsync(copied.Id))!.StateChangedAt, "spostare in avanti non è un cambio di stato");
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.SupersedeCopiesAsync(w.Marta, c, c, Make.T0));
}
/// <summary>
/// The library file goes back to an earlier one (A→B→A, or A→B→C→A: «Tieni il più grande» compares pixels or bytes
/// and is not transitive; a rebuild keeps the file on disk): the copy matches again and is never superseded by itself.
/// </summary>
[TestMethod]
public async Task SupersedingBackToTheOriginalRevivesTheCopy()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var (a, b, c) = (Make.Sha(1), Make.Sha(2), Make.Sha(3));
var identity = new ExportCopyIdentity(w.General, w.Marta, a, ExportVariant.Whole, ExportFormat.Original, null);
var copied = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var removed = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own) with { State = ExportCopyState.Removed });
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(1)));
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, b, a, Make.T0.AddDays(2)));
var back = (await db.Exports.GetCopyAsync(copied.Id))!;
Assert.AreEqual(ExportCopyState.Copied, back.State, "la copia è di nuovo uguale al file della libreria");
Assert.IsNull(back.SupersededBySha256);
Assert.AreEqual(Make.T0.AddDays(2), back.StateChangedAt);
Assert.AreEqual(copied.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
var stillRemoved = (await db.Exports.GetCopyAsync(removed.Id))!;
Assert.AreEqual(ExportCopyState.Removed, stillRemoved.State, "un «Tolto» resta tolto");
Assert.IsNull(stillRemoved.SupersededBySha256);
Assert.IsEmpty(await db.Exports.ListCopiesBySha256Async(b));
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(3)));
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, b, c, Make.T0.AddDays(4)));
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, c, a, Make.T0.AddDays(5)));
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(copied.Id))!.State, "A→B→C→A");
Assert.IsNull((await db.Exports.GetCopyAsync(removed.Id))!.SupersededBySha256);
Assert.AreEqual(0L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE superseded_by_sha256 = source_sha256"));
}
[TestMethod]
public async Task SupersedingBackKeepsTheCurrentCopyOfTheIdentity()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var (a, b) = (Make.Sha(1), Make.Sha(2));
var identity = new ExportCopyIdentity(w.General, w.Marta, a, ExportVariant.Whole, ExportFormat.Original, null);
// Two Superseded rows of one identity: only the newest can come back, the unique index allows one current row.
var oldest = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(1));
var newer = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg")); // «Copia di nuovo»
await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(2));
Assert.AreEqual(1, await db.Exports.SupersedeCopiesAsync(w.Marta, b, a, Make.T0.AddDays(3)));
Assert.AreEqual(newer.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
var history = (await db.Exports.GetCopyAsync(oldest.Id))!;
Assert.AreEqual(ExportCopyState.Superseded, history.State, "resta storia, superata dal file di prima");
Assert.AreEqual(b, history.SupersededBySha256);
// A current row made meanwhile (copied again while the library held B): the Superseded row stays history.
await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(4));
var third = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (3).jpg"));
Assert.AreEqual(0, await db.Exports.SupersedeCopiesAsync(w.Marta, b, a, Make.T0.AddDays(5)));
Assert.AreEqual(third.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(newer.Id))!.State);
Assert.AreEqual(b, (await db.Exports.GetCopyAsync(newer.Id))!.SupersededBySha256);
}
/// <summary>The partial unique indexes of 0003 reach the callers as <see cref="DuplicateRecordException"/>, never as a SQLite error.</summary>
[TestMethod]
public async Task CollisionsAreDuplicateRecords()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"Z:\Altra")), "ux_export_destination_general");
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Marta, @"Z:\Marta")), "ux_export_destination_account");
Assert.HasCount(2, await db.Exports.ListDestinationsAsync(includeRetired: true));
var first = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg")), "ux_export_copy_identity");
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddCopyAsync(w.WholeCopy("MARTA.demo/a.jpg", account: w.Luca, media: w.LucaMedia)), "ux_export_copy_path");
await db.Exports.UpdateCopyAsync(first with { State = ExportCopyState.Removed });
var second = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg"));
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.UpdateCopyAsync(first), "un «Tolto» non torna copiato accanto alla copia corrente");
Assert.AreEqual(ExportCopyState.Removed, (await db.Exports.GetCopyAsync(first.Id))!.State);
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(second.Id))!.State);
var pending = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Jpg, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Conversions.AddAsync(pending with { Id = 0 }), "ux_media_conversion_current");
var removed = pending with { State = MediaConversionState.Removed, RelativePath = "post/a.jpg.jpg", Bytes = 1, Sha256 = Make.Sha(2), ConvertedAt = Make.T0 };
await db.Conversions.UpdateAsync(removed);
await db.Conversions.AddAsync(pending with { Id = 0 });
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Conversions.UpdateAsync(removed with { State = MediaConversionState.Converted }), "ux_media_conversion_current");
Assert.AreEqual(MediaConversionState.Removed, (await db.Conversions.GetAsync(pending.Id))!.State);
}
[TestMethod]
public async Task RunsAndItemsRoundTrip()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var old = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0, State = ExportRunState.Completed, CompletedAt = Make.T0.AddMinutes(5) });
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0.AddDays(1), Origin = ExportRunOrigin.Automatic });
var recognize = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.Own, StartedAt = Make.T0.AddDays(2), Kind = ExportRunKind.Recognize, State = ExportRunState.Paused, LastError = "Disco non raggiungibile" });
Assert.AreEqual(recognize, await db.Exports.GetRunAsync(recognize.Id));
CollectionAssert.AreEqual(new[] { recognize.Id, run.Id, old.Id }, (await db.Exports.ListRunsAsync()).Select(r => r.Id).ToArray());
CollectionAssert.AreEqual(new[] { run.Id, recognize.Id }, (await db.Exports.ListUnfinishedRunsAsync()).Select(r => r.Id).ToArray());
var interrupted = run with { State = ExportRunState.Interrupted };
await db.Exports.UpdateRunAsync(interrupted);
Assert.AreEqual(interrupted, await db.Exports.GetRunAsync(run.Id));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateRunAsync(run with { Id = 9999 }));
ExportItem[] items =
[
new() { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1) },
new() { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), Variant = ExportVariant.Converted, Format = ExportFormat.Jpg },
new() { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), Variant = ExportVariant.Frame, Format = ExportFormat.Png, FrameAt = TimeSpan.FromSeconds(2) },
new() { RunId = run.Id, MediaId = w.LucaMedia, AccountId = w.Luca, SourceSha256 = Make.Sha(1) },
];
await db.Exports.AddItemsAsync(items);
await db.Exports.AddItemsAsync(items); // resume: nothing twice
await db.Exports.AddItemsAsync([items[0] with { RunId = old.Id }]);
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddItemsAsync([items[0] with { AccountId = null }]));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddItemsAsync([items[0] with { MediaId = null }]), "senza file non si riconoscerebbe alla ripresa");
var listed = await db.Exports.ListItemsAsync(new() { RunId = run.Id });
Assert.HasCount(4, listed);
Assert.AreEqual(items[2] with { Id = listed[2].Id }, listed[2]);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var done = listed[0] with { State = ExportItemState.Copied, RelativePath = @"marta.demo\a.jpg", CopyId = copy.Id };
var skipped = listed[3] with { State = ExportItemState.Skipped, Note = "AnimatedImage" };
await db.Exports.UpdateItemsAsync([done, skipped]);
Assert.AreEqual(done with { RelativePath = "marta.demo/a.jpg" }, await db.Exports.GetItemAsync(done.Id));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateItemsAsync([done with { Id = 9999 }]));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateItemsAsync([done with { RunId = old.Id }]));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateItemsAsync([done with { MediaId = w.LucaMedia }]));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateItemsAsync([done with { Variant = ExportVariant.Converted, Format = ExportFormat.Png }]));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateItemsAsync([listed[2] with { FrameAt = TimeSpan.FromSeconds(3) }]));
Assert.AreEqual(done with { RelativePath = "marta.demo/a.jpg" }, await db.Exports.GetItemAsync(done.Id), "l'identità del file resta");
CollectionAssert.AreEqual(new[] { listed[1].Id, listed[2].Id }, (await db.Exports.ListItemsAsync(new() { RunId = run.Id, State = ExportItemState.Pending })).Select(i => i.Id).ToArray());
CollectionAssert.AreEqual(new[] { listed[2].Id, listed[3].Id }, (await db.Exports.ListItemsAsync(new() { RunId = run.Id, AfterId = listed[1].Id, Limit = 5 })).Select(i => i.Id).ToArray());
CollectionAssert.AreEqual(new[] { listed[0].Id }, (await db.Exports.ListItemsAsync(new() { RunId = run.Id, Limit = 1 })).Select(i => i.Id).ToArray());
var summary = await db.Exports.GetRunSummaryAsync(run.Id);
Assert.AreEqual(4, summary.Total);
Assert.HasCount(Enum.GetValues<ExportItemState>().Length, summary.ByState);
Assert.AreEqual(2, summary.ByState[ExportItemState.Pending]);
Assert.AreEqual(1, summary.ByState[ExportItemState.Copied]);
Assert.AreEqual(1, summary.ByState[ExportItemState.Skipped]);
Assert.AreEqual(0, summary.ByState[ExportItemState.Failed]);
await db.Exports.DeleteRunAsync(run.Id);
Assert.IsNull(await db.Exports.GetRunAsync(run.Id));
Assert.IsEmpty(await db.Exports.ListItemsAsync(new() { RunId = run.Id }));
Assert.HasCount(1, await db.Exports.ListItemsAsync(new() { RunId = old.Id }), "gli altri lavori restano");
Assert.IsNotNull(await db.Exports.GetCopyAsync(copy.Id), "le copie restano");
}
[TestMethod]
public async Task VideoAnalysesKeepTheHighestAlgorithm()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(1)));
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1).ToUpperInvariant(), 1, VideoAnalysisOutcome.Still, Make.T0));
Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0), await db.VideoAnalyses.GetAsync(Make.Sha(1)));
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Moving, Make.T0.AddDays(1)));
Assert.AreEqual(2, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Algorithm, "vale l'algoritmo più alto");
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0.AddDays(2)));
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Outcome);
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)));
Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo si sostituisce");
Assert.AreEqual(2L, await ScalarAsync(db, "SELECT COUNT(*) FROM video_analysis"));
for (var i = 10; i < 710; i++)
{
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(i), 1, i % 2 == 0 ? VideoAnalysisOutcome.Still : VideoAnalysisOutcome.Moving, Make.T0));
}
var keys = Enumerable.Range(0, 800).Select(Make.Sha).ToList();
var many = await db.VideoAnalyses.GetManyAsync(keys);
Assert.HasCount(701, many);
Assert.AreEqual(2, many[Make.Sha(1)].Algorithm);
Assert.AreEqual(VideoAnalysisOutcome.Moving, many[Make.Sha(709)].Outcome);
await Assert.ThrowsExactlyAsync<ArgumentOutOfRangeException>(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0)));
}
[TestMethod]
public async Task ConversionsRoundTrip()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var pending = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Jpg, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
Assert.AreEqual(pending, await db.Conversions.GetAsync(pending.Id));
Assert.AreEqual(MediaConversionState.Pending, pending.State);
var converted = pending with
{
State = MediaConversionState.Converted,
RelativePath = "post/a.jpg.jpg",
Bytes = 900,
Sha256 = Make.Sha(2).ToUpperInvariant(),
ConvertedAt = Make.T0.AddMinutes(1),
StateChangedAt = Make.T0.AddMinutes(1),
};
await db.Conversions.UpdateAsync(converted);
Assert.AreEqual(converted with { Sha256 = Make.Sha(2) }, await db.Conversions.GetAsync(pending.Id));
CollectionAssert.AreEqual(new[] { pending.Id }, (await db.Conversions.FindBySha256Async(Make.Sha(2))).Select(c => c.Id).ToArray());
var removed = converted with { State = MediaConversionState.Removed, StateChangedAt = Make.T0.AddDays(1) };
await db.Conversions.UpdateAsync(removed);
Assert.AreEqual(MediaConversionState.Removed, (await db.Conversions.GetAsync(pending.Id))!.State);
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Conversions.UpdateAsync(converted with { RelativePath = null }));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Conversions.AddAsync(pending with { Format = ExportFormat.Original }));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Conversions.UpdateAsync(converted with { Id = 9999 }));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Conversions.UpdateAsync(converted with { Format = ExportFormat.Png }));
var png = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Png, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
var again = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Jpg, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0.AddDays(2) });
var luca = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.LucaMedia, Format = ExportFormat.WebpLossless, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
CollectionAssert.AreEqual(new[] { pending.Id, png.Id, again.Id }, (await db.Conversions.ListByMediaAsync(w.MartaMedia)).Select(c => c.Id).ToArray());
CollectionAssert.AreEqual(new[] { png.Id, again.Id, luca.Id }, (await db.Conversions.ListPendingAsync()).Select(c => c.Id).ToArray());
CollectionAssert.AreEqual(new[] { again.Id }, (await db.Conversions.ListPendingAsync(afterId: png.Id, limit: 1)).Select(c => c.Id).ToArray());
}
}
+176
View File
@@ -0,0 +1,176 @@
using Febe.Core.Domain;
using Febe.Data;
using Febe.Tests.Support;
using Microsoft.Data.Sqlite;
namespace Febe.Tests.Data;
/// <summary>
/// Two accounts with the same post (a post of marta.demo, a tagged post of luca.demo, same SHA-256), the general
/// folder and the own folder of marta.demo: the starting point of the export tests.
/// </summary>
internal sealed record ExportWorld(long Marta, long Luca, long MartaEntry, long MartaMedia, long LucaEntry, long LucaMedia, long General, long Own)
{
public static async Task<ExportWorld> CreateAsync(FebeDatabase db, string generalRoot = @"E:\Copie")
{
var marta = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var luca = await db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
var post = await db.Entries.AddAsync(Make.Entry(marta.Id, "555", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/a.jpg")]);
var tagged = await db.Entries.AddAsync(Make.Entry(luca.Id, "555", Make.T0, EntryKind.Tagged), [Make.Stored(Make.Photo(), Make.Sha(1), "taggati/a.jpg")]);
var general = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, generalRoot));
var own = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, marta.Id, @"F:\Marta"));
return new ExportWorld(marta.Id, luca.Id, post.Stored.Entry.Id, post.Stored.Media[0].Id, tagged.Stored.Entry.Id, tagged.Stored.Media[0].Id, general.Id, own.Id);
}
public static ExportDestination Destination(ExportScope scope, long? accountId, string root) => new()
{
Scope = scope,
AccountId = accountId,
RootPath = root,
ContentTypes = ContentTypes.All,
CreatedAt = Make.T0,
};
/// <summary>A whole copy of the shared photo for marta.demo in the general folder, at <paramref name="path"/>.</summary>
public ExportCopy WholeCopy(string path, long? destination = null, long? account = null, long? media = null) => new()
{
DestinationId = destination ?? General,
AccountId = account ?? Marta,
MediaId = media ?? MartaMedia,
SourceSha256 = Make.Sha(1),
Variant = ExportVariant.Whole,
State = ExportCopyState.Copied,
RelativePath = path,
Bytes = 1000,
CopySha256 = Make.Sha(1),
CopiedAt = Make.T0.AddHours(1),
};
/// <summary>A raw row of export_copy (the whole copy above), with changes.</summary>
public Dictionary<string, object?> CopyRow(params (string Column, object? Value)[] changes) => Row(
new()
{
["destination_id"] = General,
["account_id"] = Marta,
["media_id"] = MartaMedia,
["source_sha256"] = Make.Sha(1),
["variant"] = "Whole",
["format"] = "Original",
["frame_at_ms"] = null,
["state"] = "Copied",
["superseded_by_sha256"] = null,
["origin"] = "Written",
["relative_path"] = "marta.demo/a.jpg",
["bytes"] = 1000L,
["copy_sha256"] = Make.Sha(1),
["copied_at"] = 0L,
},
changes);
/// <summary>A raw row of export_destination: a retired general folder, with changes.</summary>
public static Dictionary<string, object?> DestinationRow(params (string Column, object? Value)[] changes) => Row(
new()
{
["scope"] = "General",
["account_id"] = null,
["removed_account_username"] = null,
["root_path"] = @"G:\Altra",
["content_types"] = 63L,
["photo_format"] = null,
["video_format"] = null,
["automatic"] = 0L,
["automatic_since"] = null,
["created_at"] = 0L,
["removed_at"] = 1L,
},
changes);
public Dictionary<string, object?> RunRow(params (string Column, object? Value)[] changes) => Row(
new() { ["destination_id"] = General, ["kind"] = "Copy", ["origin"] = "Manual", ["state"] = "Running", ["started_at"] = 0L },
changes);
public Dictionary<string, object?> ItemRow(long runId, params (string Column, object? Value)[] changes) => Row(
new()
{
["run_id"] = runId,
["media_id"] = MartaMedia,
["account_id"] = Marta,
["source_sha256"] = Make.Sha(1),
["variant"] = "Whole",
["format"] = "Original",
["frame_at_ms"] = null,
["state"] = "Pending",
},
changes);
public static Dictionary<string, object?> AnalysisRow(params (string Column, object? Value)[] changes) => Row(
new() { ["sha256"] = Make.Sha(5), ["algorithm"] = 1L, ["outcome"] = "Still", ["analyzed_at"] = 0L },
changes);
public Dictionary<string, object?> ConversionRow(params (string Column, object? Value)[] changes) => Row(
new() { ["media_id"] = MartaMedia, ["format"] = "Jpg", ["state"] = "Pending", ["source_sha256"] = Make.Sha(1), ["created_at"] = 0L },
changes);
/// <summary>Inserts a raw row and returns its rowid.</summary>
public static Task<long> InsertAsync(FebeDatabase db, string table, IReadOnlyDictionary<string, object?> row) =>
db.WriteAsync(
w =>
{
var c = w.Command($"INSERT INTO {table} ({string.Join(", ", row.Keys)}) VALUES ({string.Join(", ", row.Keys.Select(k => "@" + k))})");
foreach (var (column, value) in row)
{
c.With("@" + column, value);
}
c.ExecuteNonQuery();
return w.LastInsertRowId();
},
default);
/// <summary>The row breaks a constraint (SQLITE_CONSTRAINT) and is not written.</summary>
public static async Task RejectedAsync(FebeDatabase db, string table, IReadOnlyDictionary<string, object?> row, string because)
{
var error = await Assert.ThrowsExactlyAsync<SqliteException>(() => InsertAsync(db, table, row), because);
Assert.AreEqual(19, error.SqliteErrorCode, because);
}
public static Task<int> ExecuteAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
db.WriteAsync(
w =>
{
var c = w.Command(sql);
foreach (var (name, value) in parameters)
{
c.With(name, value);
}
return c.ExecuteNonQuery();
},
default);
public static Task<long> ScalarAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
db.ReadAsync(
c =>
{
var command = c.Command(sql);
foreach (var (name, value) in parameters)
{
command.With(name, value);
}
return command.ScalarInt64();
},
default);
public static Task<long> ForeignKeyProblemsAsync(FebeDatabase db) => ScalarAsync(db, "SELECT COUNT(*) FROM pragma_foreign_key_check");
private static Dictionary<string, object?> Row(Dictionary<string, object?> row, (string Column, object? Value)[] changes)
{
foreach (var (column, value) in changes)
{
row[column] = value;
}
return row;
}
}
+241
View File
@@ -11,8 +11,19 @@ public sealed class MigrationTests
[
"setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log",
"session", "incident", "event", "following", "import_run", "import_file",
"export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion",
];
/// <summary>The tables of schema version 1, which migrations 2 and 3 never rewrite.</summary>
private static readonly string[] Version1Tables =
[
"setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log",
"session", "incident", "event", "following", "import_run", "import_file",
];
private static readonly string[] ExportTables =
["export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion"];
[TestMethod]
public void EmbeddedMigrationsAreNumberedFromOne()
{
@@ -24,6 +35,8 @@ public sealed class MigrationTests
}
Assert.AreEqual("schema", migrations[0].Name);
Assert.AreEqual("ordine_scaricamento", migrations[1].Name);
Assert.AreEqual("esportazione", migrations[2].Name);
}
[TestMethod]
@@ -145,6 +158,234 @@ public sealed class MigrationTests
}
}
[TestMethod]
public async Task DatabaseAtVersion1IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(1);
[TestMethod]
public async Task DatabaseAtVersion2IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(2);
[TestMethod]
public void MigrationThreeChangesNoExistingTable()
{
using var temp = new TempFolder();
var path = temp.Combine("dati", FebeDatabase.FileName);
var all = MigrationRunner.LoadEmbedded();
Close(FebeDatabase.Open(path, all.Take(2).ToList()));
var before = SchemaOf(path, Version1Tables);
var shapesBefore = TableShapes(path, Version1Tables);
Close(FebeDatabase.Open(path, all));
CollectionAssert.AreEqual(before, SchemaOf(path, Version1Tables), "la migrazione 3 non tocca tabelle né indici esistenti");
CollectionAssert.AreEqual(shapesBefore, TableShapes(path, Version1Tables), "colonne e indici delle tabelle esistenti restano gli stessi");
}
[TestMethod]
public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched()
{
using var temp = new TempFolder();
var path = temp.Combine("dati", FebeDatabase.FileName);
await using (var db = await TestDatabase.OpenAsync(temp))
{
await db.Settings.SetAsync("prova", "1");
}
var next = MigrationRunner.LoadEmbedded().Count + 1;
SetUserVersion(path, next);
var bytes = File.ReadAllBytes(path);
var error = await Assert.ThrowsExactlyAsync<DatabaseMigrationException>(() => FebeDatabase.OpenFileAsync(path));
Assert.Contains("più recente", error.Message);
Assert.AreEqual((long)next, GetUserVersion(path));
CollectionAssert.AreEqual(bytes, File.ReadAllBytes(path), "Febe non scrive nel database più recente");
}
/// <summary>
/// A database left at an older version with data in every table is brought to the latest version: references
/// clean, data unchanged, export tables empty, no export setting written.
/// </summary>
private static async Task UpgradeKeepsEverything(int fromVersion)
{
using var temp = new TempFolder();
var path = temp.Combine("dati", FebeDatabase.FileName);
var all = MigrationRunner.LoadEmbedded();
Close(FebeDatabase.Open(path, all.Take(fromVersion).ToList()));
Fill(path, fromVersion);
var columns = ColumnsOf(path, Version1Tables);
var before = Snapshot(path, columns);
await using (var db = FebeDatabase.Open(path, all))
{
Assert.AreEqual(all.Count, db.SchemaVersion);
Assert.AreEqual(3, db.SchemaVersion);
}
using var connection = Connect(path);
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM pragma_foreign_key_check").ScalarInt64(), "foreign_key_check pulito");
Assert.AreEqual("ok", connection.Command("PRAGMA integrity_check").ExecuteScalar());
CollectionAssert.AreEqual(before, Snapshot(path, columns), "i dati di prima restano uguali");
foreach (var table in ExportTables)
{
Assert.AreEqual(0L, connection.Command($"SELECT COUNT(*) FROM {table}").ScalarInt64(), $"{table} nasce vuota");
}
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM setting WHERE key LIKE 'esportazione.%'").ScalarInt64());
if (fromVersion >= 2)
{
Assert.AreEqual("storie,post", connection.Command("SELECT download_order FROM account WHERE username = 'marta.demo'").ExecuteScalar());
Assert.AreEqual(1L, connection.Command("SELECT COUNT(*) FROM entry WHERE is_reel = 1").ScalarInt64());
}
}
/// <summary>Raw rows in every table of version 1 (and the columns of version 2), written without the stores.</summary>
private static void Fill(string path, int version)
{
using var connection = Connect(path);
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
var sha = Make.Sha(7);
var other = Make.Sha(8);
connection.Command($"""
INSERT INTO setting (key, value) VALUES ('libreria.schema', 'a/b'), ('motore.profilo', 'Prudent');
INSERT INTO account (id, instagram_id, username, state, frequency, content_types, history_depth, backfill_posts_per_day, added_at)
VALUES (1, '100', 'marta.demo', 'Active', 'Normal', 63, 'Everything', 50, 1000),
(2, '200', 'luca.demo', 'Active', 'Normal', 63, 'Everything', 50, 1000);
INSERT INTO entry (id, account_id, kind, instagram_id, published_at, state, provenance, discovered_at)
VALUES (1, 1, 'Post', '555', 2000, 'Downloaded', 'Downloaded', 2000),
(2, 2, 'Tagged', '555', 2000, 'Downloaded', 'Downloaded', 2000),
(3, 1, 'Story', '777', 3000, 'Downloaded', 'Downloaded', 3000);
INSERT INTO media (id, entry_id, position, kind, state, relative_path, bytes, sha256, downloaded_at)
VALUES (1, 1, 1, 'Photo', 'Downloaded', 'post/a.jpg', 10, '{sha}', 2100),
(2, 2, 1, 'Photo', 'Downloaded', 'taggati/a.jpg', 10, '{sha}', 2100),
(3, 3, 1, 'Video', 'Downloaded', 'storie/b.mp4', 20, '{other}', 3100);
INSERT INTO highlight (id, account_id, instagram_id, title, discovered_at) VALUES (1, 1, 'h1', 'Estate', 3000);
INSERT INTO highlight_entry (highlight_id, entry_id, position) VALUES (1, 3, 1);
INSERT INTO task (kind, account_id, due_at, state, created_at) VALUES ('Profile', 1, 4000, 'Pending', 4000);
INSERT INTO import_run (id, source_path, mode, state, started_at) VALUES (1, 'C:/vecchie', 'Copy', 'Completed', 5000);
INSERT INTO import_file (id, run_id, relative_path, folder, outcome, matched_media_id, decision, state)
VALUES (1, 1, 'marta/a.jpg', 'marta', 'ProbableDuplicate', 1, 'None', 'Analyzed');
INSERT INTO duplicate_pair (origin, reason, existing_media_id, candidate_import_file_id, decision, created_at)
VALUES ('Import', 'PerceptualHash', 1, 1, 'Pending', 5000);
INSERT INTO session (id, started_at, ended_at, action_count, outcome, summary) VALUES (1, 6000, 6500, 3, 'Completed', 'tre azioni');
INSERT INTO action_log (at, category, account_id, session_id, amount) VALUES (6100, 'Profile', 1, 1, 1);
INSERT INTO incident (at, level, signal, url, session_id, note) VALUES (6200, 'Pause', 'Http429', '/p/x', 1, 'prova');
INSERT INTO event (at, severity, code, message, account_id, session_id) VALUES (6300, 'Info', 'Downloaded', 'scaricato', 1, 1);
INSERT INTO "following" (instagram_id, username, display_name, is_private, position, read_at) VALUES ('300', 'anna.demo', 'Anna', 0, 1, 6400);
""").ExecuteNonQuery();
if (version >= 2)
{
connection.Command("UPDATE account SET download_order = 'storie,post' WHERE id = 1; UPDATE entry SET is_reel = 1 WHERE id = 1;").ExecuteNonQuery();
}
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM pragma_foreign_key_check").ScalarInt64());
foreach (var table in Version1Tables)
{
Assert.IsGreaterThan(0L, connection.Command($"SELECT COUNT(*) FROM \"{table}\"").ScalarInt64(), $"{table} ha dati prima dell'aggiornamento");
}
}
private static SqliteConnection Connect(string path)
{
var connection = new SqliteConnection($"Data Source={path};Pooling=False");
connection.Open();
return connection;
}
private static void Close(FebeDatabase db) => db.DisposeAsync().AsTask().GetAwaiter().GetResult();
/// <summary>The columns of the tables now, so a later snapshot reads the same ones.</summary>
private static Dictionary<string, string[]> ColumnsOf(string path, IEnumerable<string> tables)
{
using var connection = Connect(path);
var columns = new Dictionary<string, string[]>(StringComparer.Ordinal);
foreach (var table in tables)
{
using var r = connection.Command($"SELECT name FROM pragma_table_info('{table}') ORDER BY cid").ExecuteReader();
var names = new List<string>();
while (r.Read())
{
names.Add(r.GetString(0));
}
columns[table] = [.. names];
}
return columns;
}
/// <summary>Every row of the tables (the given columns), as text, in a stable order.</summary>
private static List<string> Snapshot(string path, Dictionary<string, string[]> columns)
{
using var connection = Connect(path);
var rows = new List<string>();
foreach (var (table, names) in columns)
{
using var r = connection.Command($"SELECT {string.Join(", ", names.Select(n => $"\"{n}\""))} FROM \"{table}\"").ExecuteReader();
var tableRows = new List<string>();
while (r.Read())
{
var values = new string[r.FieldCount];
for (var i = 0; i < r.FieldCount; i++)
{
values[i] = r.GetName(i) + "=" + (r.IsDBNull(i) ? "NULL" : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture));
}
tableRows.Add(table + ": " + string.Join(", ", values));
}
tableRows.Sort(StringComparer.Ordinal);
rows.AddRange(tableRows);
}
return rows;
}
/// <summary>The SQL of the tables and of their indexes and triggers.</summary>
private static List<string> SchemaOf(string path, IEnumerable<string> tables)
{
using var connection = Connect(path);
var list = new List<string>();
using var command = connection.Command("SELECT type || ' ' || name || ': ' || ifnull(sql, '') FROM sqlite_master WHERE tbl_name = @t ORDER BY type, name");
foreach (var table in tables)
{
command.With("@t", table);
using var r = command.ExecuteReader();
while (r.Read())
{
list.Add(r.GetString(0));
}
}
return list;
}
/// <summary>Columns (pragma_table_info) and indexes (pragma_index_list) of the tables.</summary>
private static List<string> TableShapes(string path, IEnumerable<string> tables)
{
using var connection = Connect(path);
var list = new List<string>();
foreach (var table in tables)
{
using (var r = connection.Command($"SELECT cid, name, type, \"notnull\", ifnull(dflt_value, ''), pk FROM pragma_table_info('{table}') ORDER BY cid").ExecuteReader())
{
while (r.Read())
{
list.Add($"{table} column {r.GetInt64(0)} {r.GetString(1)} {r.GetString(2)} {r.GetInt64(3)} {r.GetString(4)} {r.GetInt64(5)}");
}
}
using (var r = connection.Command($"SELECT name, \"unique\", origin, partial FROM pragma_index_list('{table}') ORDER BY name").ExecuteReader())
{
while (r.Read())
{
list.Add($"{table} index {r.GetString(0)} {r.GetInt64(1)} {r.GetString(2)} {r.GetInt64(3)}");
}
}
}
return list;
}
private static void SetUserVersion(string path, int version)
{
using var connection = new SqliteConnection($"Data Source={path};Pooling=False");
@@ -164,6 +164,10 @@ public sealed partial class SpecificationConsistencyTests
["D1 ha la migrazione 0002", "| **D1 Dashboard e ordine** |", new[] { "migrazione `0002`", "`account.download_order`", "`entry.is_reel`", "`ix_entry_discovered`", "`ix_media_entry_files`" }],
["E1 prende la migrazione 0003", "| **E1 Schema** |", new[] { "migrazione `0003`", "la `0002` è di d1" }],
["le tabelle dell'esportazione vanno nella 0003", "| `export_destination`", new[] { "migrazione `0003`" }],
["le tabelle dell'esportazione sono costruite nella 0003", "| `export_destination`", new[] { "`export_account`", "`media_conversion`", "rimuovere un account la lascia senza account", "la ritira", "la tabella `media` non cambia", "`esportazione.stesso-post`" }],
["la conversione per la libreria si registra in media_conversion", "- **per la libreria**", new[] { "`media_conversion`", "migrazione `0003`", "26 novembre 2026", "la tabella `media` non cambia" }],
["E1 ha anche export_account e media_conversion", "| **E1 Schema** |", new[] { "`export_account`", "`media_conversion`", "`exportsettings`", "versioni 1 e 2" }],
["i vincoli della 0003 sono nello schema", "- Dalla migrazione `0003` (tappa E1)", new[] { "`ux_export_copy_identity`", "`ux_export_copy_path`", "`ix_export_copy_sha256`", "`ix_export_copy_destination`", "on delete restrict", "ogni colonna di chiave esterna" }],
["gli indici di D1 sono nello schema", "- Indici su (account, data di pubblicazione)", new[] { "`0002`", "`ix_entry_discovered`", "`ix_media_entry_files`" }],
["le dipendenze dicono chi ha la 0002", "Dipendenze: C1", new[] { "la migrazione `0002` è di d1", "e1 prende la `0003`" }],
["l'icona della Dashboard è layout-dashboard", "| Navigazione |", new[] { "`layout-dashboard`", "`layout-grid`" }],
@@ -225,6 +229,14 @@ public sealed partial class SpecificationConsistencyTests
private static string Read(params string[] parts) => File.ReadAllText(Path.Combine([Root(), .. parts]));
/// <summary>The export tables of §8.3 are built by tappa E1: the row no longer says they are only planned.</summary>
[TestMethod]
public void TheExportTablesAreNoLongerOnlyPlanned()
{
var line = Read("docs", "SPECIFICA.md").Split('\n').First(l => l.StartsWith("| `export_destination`", StringComparison.Ordinal));
Assert.DoesNotContain("**Previste**", line, "§8.3: le tabelle della 0003 sono costruite");
}
[TestMethod]
[DynamicData(nameof(SettledPoints))]
public void TheSpecificationSettlesThePoint(string point, string start, string[] phrases)
@@ -0,0 +1,110 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>The settings of Impostazioni → Esportazione in the <c>setting</c> table (spec §4.10).</summary>
[TestClass]
public sealed class ExportSettingsTests
{
[TestMethod]
public async Task AnEmptyTableGivesTheDefaults()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var settings = await ExportSettings.LoadAsync(db.Settings);
Assert.AreEqual(ExportSettings.Default, settings);
Assert.AreEqual(ExportFormat.Original, settings.PhotoFormat);
Assert.AreEqual(ExportFormat.Original, settings.VideoFormat);
Assert.AreEqual(ExportFormat.Original, settings.LibraryPhotoFormat);
Assert.AreEqual(ExportFormat.Original, settings.LibraryVideoFormat);
Assert.AreEqual(SamePostCopies.OnePerAccount, settings.SamePost, "«Una copia per account» per impostazione predefinita");
Assert.IsFalse(settings.ConvertsCopies, "conversione per le copie spenta");
Assert.IsFalse(settings.ConvertsLibrary, "conversione per la libreria spenta");
Assert.AreEqual("92", ExportSettings.JpegQuality.ToString(System.Globalization.CultureInfo.InvariantCulture), "JPG a qualità 92, fissa");
}
[TestMethod]
public async Task SaveThenLoadRoundTripsAndWritesOnlyTheExportKeys()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var chosen = new ExportSettings(ExportFormat.Jpg, ExportFormat.Mp4, ExportFormat.WebpLossless, ExportFormat.Mp4, SamePostCopies.OneOnly);
await chosen.SaveAsync(db.Settings);
Assert.AreEqual(chosen, await ExportSettings.LoadAsync(db.Settings));
Assert.IsTrue(chosen.ConvertsCopies);
Assert.IsTrue(chosen.ConvertsLibrary);
var stored = await db.Settings.GetAllAsync();
CollectionAssert.AreEquivalent(ExportSettingKeys.All.ToArray(), stored.Keys.ToArray());
Assert.IsTrue(ExportSettingKeys.All.All(k => k.StartsWith("esportazione.", StringComparison.Ordinal)));
Assert.AreEqual("WebpLossless", stored[ExportSettingKeys.LibraryPhotoFormat]);
Assert.AreEqual("OneOnly", stored[ExportSettingKeys.SamePost]);
var photosOnly = new ExportSettings(PhotoFormat: ExportFormat.Png);
Assert.IsTrue(photosOnly.ConvertsCopies);
Assert.IsFalse(photosOnly.ConvertsLibrary);
}
[TestMethod]
[DataRow(ExportSettingKeys.PhotoFormat, "")]
[DataRow(ExportSettingKeys.PhotoFormat, "jpg")]
[DataRow(ExportSettingKeys.PhotoFormat, "2")]
[DataRow(ExportSettingKeys.PhotoFormat, "Jpg, Png")]
[DataRow(ExportSettingKeys.PhotoFormat, "Mp4")]
[DataRow(ExportSettingKeys.VideoFormat, "Png")]
[DataRow(ExportSettingKeys.VideoFormat, "mp4")]
[DataRow(ExportSettingKeys.LibraryPhotoFormat, "Mp4")]
[DataRow(ExportSettingKeys.LibraryPhotoFormat, "1")]
[DataRow(ExportSettingKeys.LibraryVideoFormat, "Jpg")]
[DataRow(ExportSettingKeys.SamePost, "OneEach")]
[DataRow(ExportSettingKeys.SamePost, "1")]
[DataRow(ExportSettingKeys.SamePost, "oneonly")]
public void AnInvalidValueFallsBackForItsKeyOnly(string key, string value)
{
var values = new Dictionary<string, string>(StringComparer.Ordinal)
{
[ExportSettingKeys.PhotoFormat] = "Png",
[ExportSettingKeys.VideoFormat] = "Mp4",
[ExportSettingKeys.LibraryPhotoFormat] = "Jpg",
[ExportSettingKeys.LibraryVideoFormat] = "Mp4",
[ExportSettingKeys.SamePost] = "OneOnly",
};
var valid = ExportSettings.From(values);
values[key] = value;
var read = ExportSettings.From(values);
var expected = key switch
{
ExportSettingKeys.PhotoFormat => valid with { PhotoFormat = ExportFormat.Original },
ExportSettingKeys.VideoFormat => valid with { VideoFormat = ExportFormat.Original },
ExportSettingKeys.LibraryPhotoFormat => valid with { LibraryPhotoFormat = ExportFormat.Original },
ExportSettingKeys.LibraryVideoFormat => valid with { LibraryVideoFormat = ExportFormat.Original },
_ => valid with { SamePost = SamePostCopies.OnePerAccount },
};
Assert.AreEqual(expected, read);
}
[TestMethod]
public async Task OpeningADatabaseWritesNoExportKey()
{
using var temp = new TempFolder();
await using (var fresh = await TestDatabase.OpenAsync(temp, "nuovo"))
{
Assert.IsFalse((await fresh.Settings.GetAllAsync()).Keys.Any(k => k.StartsWith("esportazione.", StringComparison.Ordinal)));
}
var path = temp.Combine("vecchio", FebeDatabase.FileName);
var all = MigrationRunner.LoadEmbedded();
await FebeDatabase.Open(path, all.Take(1).ToList()).DisposeAsync();
await using var migrated = FebeDatabase.Open(path, all);
Assert.AreEqual(all.Count, migrated.SchemaVersion);
Assert.IsFalse((await migrated.Settings.GetAllAsync()).Keys.Any(k => k.StartsWith("esportazione.", StringComparison.Ordinal)));
}
}