E1: le copie della cartella generale tornano con l'account, un rifiuto per ogni CHECK (#58)
La seconda revisione ha trovato che le copie della cartella generale di un account rimosso e aggiunto di nuovo restavano orfane per sempre: una «Tolto» o «Superato» senza file da adottare si sarebbe ricopiata da sola, contro §4.10. - export_copy tiene identificativo Instagram e nome dell'account rimosso, solo sulle copie orfane (CHECK, ix_export_copy_orphan); AccountStore.DeleteAsync li scrive. - RelinkOrphanCopiesAsync ridà all'account le sue copie della cartella generale, per identificativo o, se la copia non lo ha, per nome; AddAsync, UpdateAsync e RenameAsync lo chiamano nella loro transazione. La cartella propria resta ad AttachDestinationAsync. - Ogni CHECK della 0003 ha una prova di rifiuto su una riga valida per tutti gli altri; ambito, variante e formato sconosciuti si controllano anche sullo schema. - SPECIFICA §4.10 e §8.3, decisioni.md e stato.md aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ea4666d49b
commit
980212fb50
10 files changed
+470
-32
No files matched your search
+3
-3
@@ -301,7 +301,7 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
|
||||
**«Già copiato».**
|
||||
|
||||
- Una riga per copia (`export_copy`). Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo** (quello del segmento con il nome dell'account nella cartella generale, o l'account della cartella propria), variante (intero, convertito, fotogramma), formato e istante del fotogramma; la riga tiene anche percorso relativo, byte e SHA-256 della copia, data, stato. Si cerca per SHA-256, non per l'identificativo di Instagram, che gli importati possono non avere: un elemento eliminato con «Eliminalo e lascia che torni» ritrova le sue copie quando torna.
|
||||
- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta.
|
||||
- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà.
|
||||
- **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato. La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione.
|
||||
- Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»).
|
||||
- Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo»), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie».
|
||||
@@ -782,14 +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_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` |
|
||||
| `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»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; 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.
|
||||
- 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; una copia tiene identificativo e nome dell'account rimosso solo finché è senza account, e le copie orfane di un account si trovano per quelli (`ix_export_copy_orphan`); 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
|
||||
|
||||
+2
-1
@@ -570,11 +570,12 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 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 | 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. I percorsi esistenti che cambiano sono in `AccountStore`: `DeleteAsync` (due UPDATE in più, sulle destinazioni e sulle copie) e `AddAsync`, `UpdateAsync`, `RenameAsync` (il ritrovamento delle copie orfane), che non fanno nulla finché non esistono destinazioni e copie | 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 | Le copie di un account rimosso ricordano l'account: due colonne di `export_copy`, `removed_account_instagram_id` e `removed_account_username` (NOCASE), che un CHECK ammette solo con `account_id` NULL. `AccountStore.DeleteAsync`, nella stessa transazione, le scrive su tutte le copie dell'account (ogni destinazione, ogni stato) e toglie l'account lui stesso, prima del DELETE; un DELETE grezzo le lascia NULL (account sconosciuto: la copia torna solo per adozione). Quando l'account torna (`AddAsync`, e `UpdateAsync` e `RenameAsync` quando ne scrivono identificativo o nome), nella stessa transazione, le copie orfane della cartella generale (anche ritirata) gli tornano: per identificativo di Instagram se la copia ne ha uno, altrimenti per nome, senza badare alle maiuscole; mai per nome se la copia ha un identificativo, quindi un altro identificativo con lo stesso nome non le prende. `IExportStore.RelinkOrphanCopiesAsync` fa lo stesso per chi scrive quelle colonne in un altro modo. «Tolto» e «Superato» tornano sempre (nessun indice unico li tiene e il percorso non cambia); di una copia corrente torna solo la più recente per identità, e solo se l'account non ne ha già una corrente: le altre restano orfane, come storia, così `ux_export_copy_identity` e `ux_export_copy_path` non si rompono mai. Le copie della cartella propria tornano solo con `AttachDestinationAsync` (ridare la cartella è una scelta di Alberto), che come `RelinkOrphanCopyAsync` dimentica l'account rimosso. I file dei lavori (`export_item`) tengono solo il SET NULL. Indice `ix_export_copy_orphan`, parziale sulle orfane, letto in due rami (UNION ALL) | Con la sola identità per `account_id`, l'account aggiunto di nuovo (un id nuovo) non ritrovava le copie «Tolto» e «Superato» della cartella generale, che non hanno un file da adottare: `FindLatestCopyAsync` non rispondeva nulla e l'esportazione automatica le avrebbe rifatte da sola, contro §4.10. I file dei lavori non decidono «già copiato». Un OR dei due modi di confronto leggeva tutte le copie della cartella generale a ogni account aggiunto; `ExportLookupsUseTheirIndex` controlla il piano |
|
||||
| 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 |
|
||||
|
||||
+21
-8
@@ -22,16 +22,29 @@ comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue.
|
||||
- **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.
|
||||
- I percorsi esistenti che cambiano sono in `AccountStore`: `DeleteAsync`, prima di cancellare l'account, spegne
|
||||
«Automatica» delle sue cartelle (dimenticando «Solo i nuovi») e vi scrive il suo nome, e scrive identificativo di
|
||||
Instagram e nome sulle sue copie togliendone l'account; `AddAsync`, `UpdateAsync` e `RenameAsync` ridanno all'account
|
||||
le sue copie orfane della cartella generale. Finché non ci sono destinazioni e copie non fanno 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.
|
||||
sempre il suo file della libreria, le collisioni con gli indici unici arrivano come `DuplicateRecordException`, e la
|
||||
prova dell'aggiornamento riempie tutte le quindici tabelle della versione 1. Righe in `decisioni.md`.
|
||||
- Seconda revisione: le copie della cartella generale di un account rimosso e aggiunto di nuovo (un id nuovo) si
|
||||
perdevano, e una «Tolto» o «Superato» senza file da adottare si sarebbe ricopiata da sola (§4.10). Ora
|
||||
`export_copy` tiene identificativo e nome dell'account rimosso (`removed_account_instagram_id`,
|
||||
`removed_account_username`, solo sulle orfane, `ix_export_copy_orphan`) e l'account che torna le ritrova
|
||||
(`RelinkOrphanCopiesAsync`, per identificativo, per nome solo se la copia non lo ha; una copia corrente solo se
|
||||
l'account non ne ha già una della stessa identità); la cartella propria resta ad `AttachDestinationAsync`. Le prove
|
||||
dei vincoli hanno ora un rifiuto per ogni CHECK della `0003` (lunghezze, byte e istanti non negativi, i file dei
|
||||
convertiti per stato, le colonne nuove), ognuno costruito su una riga valida per tutti gli altri CHECK; fanno
|
||||
eccezione ambito, variante e formato sconosciuti, che rompono per forza anche i CHECK di coppia (ambito con account,
|
||||
variante con formato): per quegli elenchi la prova legge lo schema.
|
||||
- Controlli, su Windows, dopo la seconda revisione: `dotnet build -warnaserror` 0 avvisi, 0 errori; `dotnet test
|
||||
tests/Febe.Tests` 2883 superate, 96 ignorate (quelle con Chromium e Xvfb, solo nella CI), 0 non superate; `dotnet test
|
||||
tests/Febe.Tests.Windows` 24 superate (alla prima esecuzione una non superata, di cui l'uscita ridotta non ha tenuto il
|
||||
nome; le due riesecuzioni verdi: E1 non tocca nulla di quel progetto). Togliendo dalla `0003` quattro CHECK (file dei convertiti, byte della copia,
|
||||
account rimosso solo sulle orfane, «Automatica» booleana) cadono le prove che li riguardano.
|
||||
- **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`
|
||||
|
||||
@@ -30,11 +30,17 @@ public interface IAccountStore
|
||||
|
||||
Task<AccountStats> GetStatsAsync(long accountId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Adds an account and returns it with its key.</summary>
|
||||
/// <summary>
|
||||
/// Adds an account and returns it with its key. In the same transaction the account gets back its orphan copies of
|
||||
/// the general export folder, if it was removed before (<see cref="IExportStore.RelinkOrphanCopiesAsync"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="DuplicateRecordException">Another account has the same Instagram identifier, or is already «Tu».</exception>
|
||||
Task<Account> AddAsync(Account account, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Replaces every field of an existing account (settings screen).</summary>
|
||||
/// <summary>
|
||||
/// Replaces every field of an existing account (settings screen); with its Instagram id and user name written, it
|
||||
/// gets back its orphan copies of the general export folder as in <see cref="AddAsync"/>.
|
||||
/// </summary>
|
||||
Task UpdateAsync(Account account, CancellationToken ct = default);
|
||||
|
||||
Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default);
|
||||
@@ -47,7 +53,8 @@ public interface IAccountStore
|
||||
|
||||
/// <summary>
|
||||
/// Records a rename seen in the data (spec §4.2): updates the user name, keeps the folder (a default folder is
|
||||
/// pinned to the old name) and raises the «Renamed» notice.
|
||||
/// pinned to the old name) and raises the «Renamed» notice; with the new name, the account gets back its orphan copies
|
||||
/// of the general export folder as in <see cref="AddAsync"/>.
|
||||
/// </summary>
|
||||
Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
@@ -61,7 +68,8 @@ public interface IAccountStore
|
||||
/// 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). Its export destinations stay, without account and with the user name;
|
||||
/// its «Esporta questo account» choice goes with it (spec §4.10).
|
||||
/// its export copies stay, without account and with its Instagram id and user name, so they come back if the account
|
||||
/// is added again; its «Esporta questo account» choice goes with it (spec §4.10).
|
||||
/// </summary>
|
||||
Task DeleteAsync(long accountId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
@@ -99,12 +99,26 @@ public interface IExportStore
|
||||
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.
|
||||
/// Re-links an orphan row (account removed) to a re-added account, when its file is adopted again, and forgets the
|
||||
/// removed account kept on it.
|
||||
/// <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>
|
||||
/// Gives an account its orphan copies of the general folder (retired rows included), in every state, so a Removed or
|
||||
/// Superseded copy is never copied again by itself after the account was removed and added again (spec §4.10). A row
|
||||
/// matches by the Instagram id of the removed account when the row has one (only an account with that id), else by
|
||||
/// its user name, ignoring ASCII case. A current (Copied or Failed) row comes back only as the newest of its identity
|
||||
/// and only if the account has no current row of that identity: the others stay orphans. Copies of an own folder
|
||||
/// come back only with <see cref="AttachDestinationAsync"/>. Uses the account's current Instagram id and user name;
|
||||
/// <c>IAccountStore</c> already runs it when an account is added or its id or name is written, so callers need it
|
||||
/// only after writing those columns some other way. Returns the rows re-linked; <see cref="KeyNotFoundException"/>
|
||||
/// for a missing account.
|
||||
/// </summary>
|
||||
Task<int> RelinkOrphanCopiesAsync(long accountId, 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
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
-- 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,
|
||||
-- Only new tables and indexes: no column or index of the existing tables changes. The only existing paths that touch
|
||||
-- the new tables are in AccountStore: DeleteAsync disables the account's destinations and keeps its user name on them,
|
||||
-- and keeps its Instagram id and user name on its copies, before deleting the account; AddAsync, UpdateAsync and
|
||||
-- RenameAsync give the account back its orphan copies of the general folder (nothing to do while there are no
|
||||
-- destinations and no copies); nothing else reads or writes them yet (tappa E1: no behaviour change). Times are UTC Unix milliseconds; enumerations are their English names,
|
||||
-- checked here. Paths in a destination are relative to its root, '/' separated, NFC; paths of converted library files
|
||||
-- are relative to the account folder, like media.relative_path. Every foreign key has an index on its child column.
|
||||
|
||||
@@ -82,9 +83,18 @@ 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.
|
||||
-- the account was removed («orphan»): only AccountStore.DeleteAsync writes NULL, with the two columns below, in the
|
||||
-- transaction that deletes the account (ON DELETE SET NULL then finds nothing left to clear).
|
||||
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
|
||||
-- Instagram id and user name of the account when it was removed, on orphan rows only, so the account added again
|
||||
-- (a new account id) finds its copies again: those of the general folder come back by themselves, any state, when
|
||||
-- the account is added or its id or name written (by Instagram id when both have one, else by user name, only for a
|
||||
-- row without one); those of its own folder when the folder is attached to it again; any row when its file is
|
||||
-- adopted again by path. Both NULL on an orphan whose account is unknown (a raw delete): it comes back only by
|
||||
-- adoption. Without them a Removed or Superseded row of the general folder, which has no file to adopt, would be
|
||||
-- lost to the account added again and its file copied again by itself (spec §4.10).
|
||||
removed_account_instagram_id TEXT CHECK (removed_account_instagram_id IS NULL OR length(removed_account_instagram_id) > 0),
|
||||
removed_account_username TEXT COLLATE NOCASE CHECK (removed_account_username IS NULL OR length(removed_account_username) > 0),
|
||||
media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
|
||||
source_sha256 TEXT NOT NULL CHECK (length(source_sha256) = 64),
|
||||
variant TEXT NOT NULL CHECK (variant IN ('Whole', 'Converted', 'Frame')),
|
||||
@@ -115,7 +125,9 @@ CREATE TABLE export_copy (
|
||||
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)
|
||||
CHECK (superseded_by_sha256 IS NULL OR superseded_by_sha256 <> source_sha256),
|
||||
-- The removed account is remembered only while the row has no account: re-linking clears it.
|
||||
CHECK (account_id IS NULL OR (removed_account_instagram_id IS NULL AND removed_account_username IS NULL))
|
||||
);
|
||||
|
||||
-- The copy identity: one current row (Copied or Failed) per identity. NULL account_id (orphan) is distinct.
|
||||
@@ -141,6 +153,9 @@ CREATE INDEX ix_export_copy_superseded_by ON export_copy (superseded_by_sha256,
|
||||
-- Foreign keys with SET NULL.
|
||||
CREATE INDEX ix_export_copy_media ON export_copy (media_id) WHERE media_id IS NOT NULL;
|
||||
CREATE INDEX ix_export_copy_account ON export_copy (account_id) WHERE account_id IS NOT NULL;
|
||||
-- The orphan copies of a removed account, by its Instagram id, or by its user name for rows without one (re-linking).
|
||||
CREATE INDEX ix_export_copy_orphan ON export_copy (removed_account_instagram_id, removed_account_username)
|
||||
WHERE account_id IS NULL;
|
||||
|
||||
-- An export job (on the model of import_run): «Copia in…», the automatic export, «Riconosci le copie già presenti».
|
||||
-- Interrupted (Febe closed) and Paused (destination not reachable) runs resume from their pending items.
|
||||
|
||||
@@ -301,7 +301,12 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
ex);
|
||||
}
|
||||
|
||||
return account with { Id = w.LastInsertRowId(), InstagramId = Normalize(account.InstagramId), Username = NormalizeUsername(account.Username) };
|
||||
var added = account with { Id = w.LastInsertRowId(), InstagramId = Normalize(account.InstagramId), Username = NormalizeUsername(account.Username) };
|
||||
|
||||
// An account removed before and added again (a new id) gets back its copies of the general folder, so
|
||||
// its Removed and Superseded copies are never copied again by themselves (spec §4.10).
|
||||
ExportStore.RelinkOrphanCopies(w, added.Id, added.InstagramId, added.Username);
|
||||
return added;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
@@ -337,6 +342,9 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
{
|
||||
throw new DuplicateRecordException("Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente.", ex);
|
||||
}
|
||||
|
||||
// The Instagram id may be known only now (an imported account): its copies come back as in AddAsync.
|
||||
ExportStore.RelinkOrphanCopies(w, account.Id, Normalize(account.InstagramId), NormalizeUsername(account.Username));
|
||||
},
|
||||
ct);
|
||||
}
|
||||
@@ -407,7 +415,8 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
w =>
|
||||
{
|
||||
string? oldName;
|
||||
using (var r = w.Command("SELECT username, folder FROM account WHERE id = @id").With("@id", accountId).ExecuteReader())
|
||||
string? instagramId;
|
||||
using (var r = w.Command("SELECT username, folder, instagram_id FROM account WHERE id = @id").With("@id", accountId).ExecuteReader())
|
||||
{
|
||||
if (!r.Read())
|
||||
{
|
||||
@@ -415,6 +424,7 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
}
|
||||
|
||||
oldName = r.GetString(0);
|
||||
instagramId = r.GetTextOrNull(2);
|
||||
}
|
||||
|
||||
if (string.Equals(oldName, name, StringComparison.Ordinal))
|
||||
@@ -434,6 +444,7 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
.With("@renamed", (long)AccountNotices.Renamed)
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery();
|
||||
ExportStore.RelinkOrphanCopies(w, accountId, instagramId, name);
|
||||
},
|
||||
ct);
|
||||
}
|
||||
@@ -478,6 +489,18 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
automatic = 0, automatic_since = NULL
|
||||
WHERE account_id = @id
|
||||
""").With("@id", accountId).ExecuteNonQuery();
|
||||
|
||||
// Its copies stay, in every destination and state, without account but with its Instagram id and user
|
||||
// name, so the account added again finds them (ExportStore.RelinkOrphanCopies): a Removed or Superseded
|
||||
// copy of the general folder has no file to adopt again. A CHECK allows them only without account, so
|
||||
// the link is cleared here, not by ON DELETE SET NULL. Job items keep only the SET NULL: they are not
|
||||
// what «già copiato» reads.
|
||||
w.Command("""
|
||||
UPDATE export_copy SET account_id = NULL,
|
||||
removed_account_instagram_id = (SELECT instagram_id FROM account WHERE id = @id),
|
||||
removed_account_username = (SELECT username FROM account WHERE id = @id)
|
||||
WHERE account_id = @id
|
||||
""").With("@id", accountId).ExecuteNonQuery();
|
||||
w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery();
|
||||
},
|
||||
ct);
|
||||
|
||||
@@ -379,7 +379,10 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
.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")
|
||||
w.Command("""
|
||||
UPDATE export_copy SET account_id = @a, removed_account_instagram_id = NULL, removed_account_username = NULL
|
||||
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}.");
|
||||
},
|
||||
@@ -553,13 +556,92 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
}
|
||||
|
||||
Unique(
|
||||
w.Command("UPDATE export_copy SET account_id = @a, media_id = coalesce(@m, media_id), state_changed_at = @at WHERE id = @id")
|
||||
w.Command("""
|
||||
UPDATE export_copy SET account_id = @a, removed_account_instagram_id = NULL, removed_account_username = NULL,
|
||||
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> RelinkOrphanCopiesAsync(long accountId, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
string? instagramId;
|
||||
string username;
|
||||
using (var r = w.Command("SELECT instagram_id, username FROM account WHERE id = @a").With("@a", accountId).ExecuteReader())
|
||||
{
|
||||
if (!r.Read())
|
||||
{
|
||||
throw new KeyNotFoundException($"Account {accountId} non trovato.");
|
||||
}
|
||||
|
||||
instagramId = r.GetTextOrNull(0);
|
||||
username = r.GetString(1);
|
||||
}
|
||||
|
||||
return RelinkOrphanCopies(w, accountId, instagramId, username);
|
||||
},
|
||||
ct);
|
||||
|
||||
/// <summary>
|
||||
/// The orphan copies of the general folder (retired rows included) whose removed account is this one (@iid, @u): by
|
||||
/// Instagram id when the row has one, else by user name (NOCASE). Two branches over ix_export_copy_orphan, so the
|
||||
/// lookup never walks the copies of the general folder (an OR of the two would).
|
||||
/// </summary>
|
||||
private const string OrphansOfAccount = """
|
||||
o.id IN (
|
||||
SELECT id FROM export_copy WHERE account_id IS NULL AND removed_account_instagram_id = @iid
|
||||
UNION ALL
|
||||
SELECT id FROM export_copy WHERE account_id IS NULL AND removed_account_instagram_id IS NULL AND removed_account_username = @u)
|
||||
AND o.destination_id IN (SELECT id FROM export_destination WHERE scope = 'General')
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// Current (Copied or Failed) orphans come back only as the newest of their identity, and only when the account has
|
||||
/// no current row of that identity: the others stay orphans, as history, so ux_export_copy_identity is never broken
|
||||
/// (a user name can match an account that already has copies, and two current orphans of one identity can exist).
|
||||
/// </summary>
|
||||
internal const string RelinkCurrentOrphansSql = $"""
|
||||
UPDATE export_copy SET account_id = @a, removed_account_instagram_id = NULL, removed_account_username = NULL
|
||||
WHERE id IN (
|
||||
SELECT max(o.id) FROM export_copy o
|
||||
WHERE {OrphansOfAccount} AND o.state IN ('Copied', 'Failed')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM export_copy c
|
||||
WHERE c.account_id = @a AND c.destination_id = o.destination_id AND c.source_sha256 = o.source_sha256
|
||||
AND c.variant = o.variant AND c.format = o.format AND ifnull(c.frame_at_ms, -1) = ifnull(o.frame_at_ms, -1)
|
||||
AND c.state IN ('Copied', 'Failed'))
|
||||
GROUP BY o.destination_id, o.source_sha256, o.variant, o.format, ifnull(o.frame_at_ms, -1))
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// Removed and Superseded orphans always come back: no unique index holds them by identity, and the path does not
|
||||
/// change, so ux_export_copy_path cannot be broken either.
|
||||
/// </summary>
|
||||
internal const string RelinkHistoryOrphansSql = $"""
|
||||
UPDATE export_copy AS o SET account_id = @a, removed_account_instagram_id = NULL, removed_account_username = NULL
|
||||
WHERE {OrphansOfAccount} AND o.state IN ('Removed', 'Superseded')
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// Gives an account its orphan copies of the general folder (see the two statements above). Run inside the
|
||||
/// transaction of the caller: AccountStore.AddAsync, UpdateAsync, RenameAsync and <see cref="RelinkOrphanCopiesAsync"/>.
|
||||
/// Copies of an own folder are left to <see cref="AttachDestinationAsync"/>, a choice of Alberto.
|
||||
/// </summary>
|
||||
internal static int RelinkOrphanCopies(WriteContext w, long accountId, string? instagramId, string username)
|
||||
{
|
||||
var current = w.Command(RelinkCurrentOrphansSql)
|
||||
.With("@a", accountId).With("@iid", Sql.Text(instagramId)).With("@u", username).ExecuteNonQuery();
|
||||
var history = w.Command(RelinkHistoryOrphansSql)
|
||||
.With("@a", accountId).With("@iid", Sql.Text(instagramId)).With("@u", username).ExecuteNonQuery();
|
||||
return current + history;
|
||||
}
|
||||
|
||||
public Task<int> SupersedeCopiesAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
var old = ExportValues.Sha(oldSha256, nameof(oldSha256));
|
||||
|
||||
@@ -30,13 +30,25 @@ public sealed class ExportConstraintTests
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow());
|
||||
await InsertAsync(db, "export_copy", w.CopyRow());
|
||||
|
||||
// Each row below breaks only the CHECK it names, but three: an unknown scope also breaks the two CHECKs that pair
|
||||
// scope with account and user name (one wants both NULL unless 'Account', the other one of them set unless
|
||||
// 'General': no other scope satisfies both), and an unknown variant or format also breaks the CHECK that pairs
|
||||
// variant with format, which lists the valid ones itself. No row can break those IN lists alone, so that they
|
||||
// are still declared is read from the schema.
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Tutti")), "ambito sconosciuto");
|
||||
await SchemaDeclaresAsync(db, "export_destination", "CHECK (scope IN ('General', 'Account'))");
|
||||
foreach (var table in new[] { "export_copy", "export_item" })
|
||||
{
|
||||
await SchemaDeclaresAsync(db, table, "CHECK (variant IN ('Whole', 'Converted', 'Frame'))");
|
||||
await SchemaDeclaresAsync(db, table, "CHECK (format IN ('Original', 'Jpg', 'Png', 'WebpLossless', 'Mp4'))");
|
||||
}
|
||||
|
||||
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(("variant", "Intero"), ("copy_sha256", Make.Sha(2)), ("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");
|
||||
@@ -114,6 +126,95 @@ public sealed class ExportConstraintTests
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryConversionPastPendingAndFailedHadAFile()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
foreach (var state in new[] { "Converted", "Superseded", "Removed" })
|
||||
{
|
||||
foreach (var missing in new[] { "relative_path", "bytes", "sha256", "converted_at" })
|
||||
{
|
||||
await RejectedAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("state", state), (missing, null)), $"{state} senza {missing}");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var state in new[] { "Converted", "Superseded", "Removed" })
|
||||
{
|
||||
await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("state", state)));
|
||||
}
|
||||
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow(("format", "Png")));
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow(("format", "WebpLossless"), ("state", "Failed")));
|
||||
}
|
||||
|
||||
/// <summary>The CHECKs on lengths, counts, instants and the «Automatica» switch: each row breaks that CHECK alone (the same row with a valid value is accepted).</summary>
|
||||
[TestMethod]
|
||||
public async Task LengthsCountsInstantsAndSwitchesAreChecked()
|
||||
{
|
||||
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 column in new[] { "label", "naming_scheme", "highlight_naming_scheme", "profile_naming_scheme" })
|
||||
{
|
||||
await RejectedAsync(db, "export_destination", DestinationRow((column, "")), $"{column} vuoto");
|
||||
await InsertAsync(db, "export_destination", DestinationRow((column, "x")));
|
||||
}
|
||||
|
||||
(string, object?)[] orphanFolder = [("scope", "Account"), ("removed_at", 1L)];
|
||||
await RejectedAsync(db, "export_destination", DestinationRow([.. orphanFolder, ("removed_account_username", "")]), "nome dell'account rimosso vuoto");
|
||||
await InsertAsync(db, "export_destination", DestinationRow([.. orphanFolder, ("removed_account_username", "x")]));
|
||||
(string, object?)[] lucaFolder = [("scope", "Account"), ("account_id", w.Luca), ("removed_at", null)];
|
||||
await RejectedAsync(db, "export_destination", DestinationRow([.. lucaFolder, ("automatic", 2L)]), "«Automatica» non booleana");
|
||||
await InsertAsync(db, "export_destination", DestinationRow([.. lucaFolder, ("automatic", 1L)]));
|
||||
|
||||
(string, object?)[] frame = [("variant", "Frame"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2))];
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow([.. frame, ("frame_at_ms", -1L), ("relative_path", "f/1.jpg")]), "istante negativo della copia");
|
||||
await InsertAsync(db, "export_copy", w.CopyRow([.. frame, ("frame_at_ms", 0L), ("relative_path", "f/1.jpg")]));
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", -1L)), "istante negativo del file");
|
||||
await InsertAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 0L)));
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("bytes", -1L), ("relative_path", "b/1.jpg")), "byte negativi della copia");
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("bytes", 0L), ("relative_path", "b/1.jpg")));
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("relative_path", "")), "percorso vuoto del file");
|
||||
await InsertAsync(db, "export_item", w.ItemRow(run, ("relative_path", "marta.demo/a.jpg")));
|
||||
|
||||
await RejectedAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("bytes", -1L)), "byte negativi del convertito");
|
||||
await RejectedAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("relative_path", "")), "percorso vuoto del convertito");
|
||||
await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("bytes", 0L)));
|
||||
}
|
||||
|
||||
/// <summary>The removed account kept on a copy: only on a row without account, never empty, and both may be unknown.</summary>
|
||||
[TestMethod]
|
||||
public async Task TheRemovedAccountIsKeptOnlyOnOrphanCopies()
|
||||
{
|
||||
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(("removed_account_username", "marta.demo"), ("relative_path", "o/1.jpg")), "un account e il nome di un account rimosso");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("removed_account_instagram_id", "100"), ("relative_path", "o/2.jpg")), "un account e l'identificativo di un account rimosso");
|
||||
|
||||
(string, object?)[] orphan = [("account_id", null)];
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow([.. orphan, ("removed_account_username", ""), ("relative_path", "o/3.jpg")]), "nome vuoto");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow([.. orphan, ("removed_account_instagram_id", ""), ("relative_path", "o/4.jpg")]), "identificativo vuoto");
|
||||
|
||||
await InsertAsync(db, "export_copy", w.CopyRow([.. orphan, ("removed_account_instagram_id", "100"), ("removed_account_username", "marta.demo"), ("relative_path", "o/1.jpg")]));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow([.. orphan, ("removed_account_username", "marta.demo"), ("relative_path", "o/2.jpg")]));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow([.. orphan, ("relative_path", "o/3.jpg")]));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "o/4.jpg")));
|
||||
}
|
||||
|
||||
private static async Task SchemaDeclaresAsync(FebeDatabase db, string table, string fragment)
|
||||
{
|
||||
var sql = await db.ReadAsync(c => (string)c.Command("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = @t").With("@t", table).ExecuteScalar()!, default);
|
||||
Assert.Contains(fragment, sql, $"{table}: {fragment}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SupersededNeedsTheFileThatTookItsPlace()
|
||||
{
|
||||
@@ -155,8 +256,16 @@ public sealed class ExportConstraintTests
|
||||
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));
|
||||
private static Dictionary<string, object?> Converted(ExportWorld w, string format, string sha256, params (string Column, object? Value)[] changes)
|
||||
{
|
||||
var row = w.ConversionRow(("format", format), ("state", "Converted"), ("relative_path", $"post/a.jpg.{format}"), ("bytes", 1L), ("sha256", sha256), ("converted_at", 0L));
|
||||
foreach (var (column, value) in changes)
|
||||
{
|
||||
row[column] = value;
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DestinationsKeepTheirRules()
|
||||
@@ -349,7 +458,11 @@ public sealed class ExportConstraintTests
|
||||
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");
|
||||
|
||||
// The general copy of an unknown account (a raw delete would leave it so): it comes back only by adoption.
|
||||
await ExecuteAsync(db, "UPDATE export_copy SET removed_account_instagram_id = NULL, removed_account_username = NULL WHERE id = @id", ("@id", generalCopy.Id));
|
||||
var again = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(ownCopy.Id))!.AccountId, "le copie della cartella propria tornano solo quando Alberto gliela ridà");
|
||||
await db.Exports.AttachDestinationAsync(w.Own, again.Id);
|
||||
|
||||
var own = (await db.Exports.GetDestinationAsync(w.Own))!;
|
||||
@@ -361,7 +474,8 @@ public sealed class ExportConstraintTests
|
||||
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");
|
||||
Assert.AreEqual(1L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE id = @id AND removed_account_username IS NULL AND removed_account_instagram_id IS NULL", ("@id", ownCopy.Id)), "e l'account rimosso si dimentica");
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(generalCopy.Id))!.AccountId, "una copia orfana di un account sconosciuto resta orfana finché non si adotta");
|
||||
|
||||
var relinked = await db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0.AddDays(2));
|
||||
Assert.AreEqual(again.Id, relinked.AccountId);
|
||||
@@ -499,6 +613,20 @@ public sealed class ExportConstraintTests
|
||||
}
|
||||
}
|
||||
|
||||
// Re-linking at each added account reads the orphans of that account through their index, never the copies of
|
||||
// the general folder (the handful of destinations is scanned, and the orphans found are grouped).
|
||||
foreach (var (name, sql) in new[] { ("RelinkCurrentOrphansSql", ExportStore.RelinkCurrentOrphansSql), ("RelinkHistoryOrphansSql", ExportStore.RelinkHistoryOrphansSql) })
|
||||
{
|
||||
var plan = await PlanAsync(db, sql, ("@a", w.Marta), ("@iid", "100"), ("@u", "marta.demo"));
|
||||
if (!plan.Contains("SEARCH o USING INTEGER PRIMARY KEY", StringComparison.Ordinal)
|
||||
|| !plan.Contains("ix_export_copy_orphan (removed_account_instagram_id=?)", StringComparison.Ordinal)
|
||||
|| !plan.Contains("ix_export_copy_orphan (removed_account_instagram_id=? AND removed_account_username=?)", StringComparison.Ordinal)
|
||||
|| plan.Contains("SCAN o", StringComparison.Ordinal) || plan.Contains("SCAN export_copy", StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"{name}: {plan}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}");
|
||||
}
|
||||
|
||||
|
||||
@@ -338,6 +338,160 @@ public sealed class ExportStoreTests
|
||||
Assert.AreEqual(b, (await db.Exports.GetCopyAsync(newer.Id))!.SupersededBySha256);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spec §4.10: «Tolto e Superato non si ricopiano mai da soli», also after the account was removed and added again
|
||||
/// (a new account id): its copies of the general folder come back by its Instagram id, in every state.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task RemovedCopiesOfTheGeneralFolderComeBackWithTheAccount()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
await db.Exports.UpdateDestinationAsync((await db.Exports.GetDestinationAsync(w.General))! with { Automatic = true });
|
||||
var removed = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Removed, StateChangedAt = Make.T0.AddDays(1) });
|
||||
var superseded = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg") with
|
||||
{
|
||||
SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(3),
|
||||
});
|
||||
var copied = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/c.png") with { Variant = ExportVariant.Converted, Format = ExportFormat.Png, CopySha256 = Make.Sha(4) });
|
||||
var own = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own) with { State = ExportCopyState.Removed });
|
||||
var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed });
|
||||
|
||||
await db.Accounts.DeleteAsync(w.Marta);
|
||||
|
||||
foreach (var id in new[] { removed.Id, superseded.Id, copied.Id, own.Id })
|
||||
{
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(id))!.AccountId);
|
||||
Assert.AreEqual(("100", "marta.demo"), await RemovedAccountAsync(db, id), "ogni copia tiene l'account rimosso, in ogni destinazione e stato");
|
||||
}
|
||||
|
||||
Assert.AreEqual((null, null), await RemovedAccountAsync(db, luca.Id), "le copie degli altri account non cambiano");
|
||||
|
||||
var again = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||
Assert.AreNotEqual(w.Marta, again.Id);
|
||||
|
||||
var identity = new ExportCopyIdentity(w.General, again.Id, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null);
|
||||
var latest = await db.Exports.FindLatestCopyAsync(identity);
|
||||
Assert.IsNotNull(latest, "la copia «Tolto» si ritrova: l'esportazione automatica non la rifà da sola");
|
||||
Assert.AreEqual(removed.Id, latest.Id);
|
||||
Assert.AreEqual(ExportCopyState.Removed, latest.State);
|
||||
Assert.AreEqual(Make.T0.AddDays(1), latest.StateChangedAt, "ritrovarla non è un cambio di stato");
|
||||
Assert.AreEqual(superseded.Id, (await db.Exports.FindLatestCopyAsync(identity with { SourceSha256 = Make.Sha(2) }))!.Id);
|
||||
Assert.AreEqual(copied.Id, (await db.Exports.FindCurrentCopyAsync(identity with { Variant = ExportVariant.Converted, Format = ExportFormat.Png }))!.Id);
|
||||
foreach (var id in new[] { removed.Id, superseded.Id, copied.Id })
|
||||
{
|
||||
Assert.AreEqual((null, null), await RemovedAccountAsync(db, id));
|
||||
}
|
||||
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(own.Id))!.AccountId, "la cartella propria torna solo quando Alberto gliela ridà");
|
||||
Assert.AreEqual(("100", "marta.demo"), await RemovedAccountAsync(db, own.Id));
|
||||
Assert.AreEqual(w.Luca, (await db.Exports.GetCopyAsync(luca.Id))!.AccountId);
|
||||
Assert.AreEqual(0, await db.Exports.RelinkOrphanCopiesAsync(again.Id), "già ritrovate");
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.RelinkOrphanCopiesAsync(9999));
|
||||
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CopiesWithoutAnInstagramIdComeBackByUserName()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var anna = await db.Accounts.AddAsync(Make.Account("anna.demo") with { InstagramId = null });
|
||||
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("anna.demo/a.jpg", account: anna.Id) with { State = ExportCopyState.Removed });
|
||||
await db.Accounts.DeleteAsync(anna.Id);
|
||||
Assert.AreEqual(((string?)null, "anna.demo"), await RemovedAccountAsync(db, copy.Id));
|
||||
|
||||
var again = await db.Accounts.AddAsync(Make.Account("@Anna.Demo", "300"));
|
||||
|
||||
Assert.AreEqual(again.Id, (await db.Exports.GetCopyAsync(copy.Id))!.AccountId, "per nome, senza badare alle maiuscole, se la copia non ha l'identificativo");
|
||||
Assert.AreEqual((null, null), await RemovedAccountAsync(db, copy.Id));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CopiesOfAnotherInstagramIdDoNotComeBack()
|
||||
{
|
||||
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") with { State = ExportCopyState.Removed });
|
||||
await db.Accounts.DeleteAsync(w.Marta);
|
||||
|
||||
var other = await db.Accounts.AddAsync(Make.Account("marta.demo", "999"));
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(copy.Id))!.AccountId, "lo stesso nome con un altro identificativo è un'altra persona");
|
||||
await db.Accounts.DeleteAsync(other.Id);
|
||||
var unknown = await db.Accounts.AddAsync(Make.Account("marta.demo") with { InstagramId = null });
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(copy.Id))!.AccountId, "la copia ha l'identificativo: il nome solo non basta");
|
||||
await db.Accounts.RenameAsync(unknown.Id, "marta.nuova", Make.T0.AddDays(1));
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(copy.Id))!.AccountId);
|
||||
Assert.AreEqual(("100", "marta.demo"), await RemovedAccountAsync(db, copy.Id));
|
||||
|
||||
// The Instagram id becomes known later (an imported account): the copies come back then.
|
||||
await db.Accounts.UpdateAsync((await db.Accounts.GetAsync(unknown.Id))! with { InstagramId = "100" });
|
||||
Assert.AreEqual(unknown.Id, (await db.Exports.GetCopyAsync(copy.Id))!.AccountId);
|
||||
Assert.AreEqual((null, null), await RemovedAccountAsync(db, copy.Id));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AdoptionByPathForgetsTheRemovedAccount()
|
||||
{
|
||||
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"));
|
||||
await db.Accounts.DeleteAsync(w.Marta);
|
||||
var other = await db.Accounts.AddAsync(Make.Account("marta.demo", "999"));
|
||||
|
||||
var adopted = await db.Exports.RelinkOrphanCopyAsync(copy.Id, other.Id, null, Make.T0.AddDays(1));
|
||||
|
||||
Assert.AreEqual(other.Id, adopted.AccountId);
|
||||
Assert.AreEqual((null, null), await RemovedAccountAsync(db, copy.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-linking by user name can meet an account that already has copies: a current row of an identity the account
|
||||
/// already holds stays an orphan, and of two current orphans of one identity only the newest comes back.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task RelinkingNeverBreaksTheIdentityOfACopy()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var anna = await db.Accounts.AddAsync(Make.Account("anna.demo") with { InstagramId = null });
|
||||
var first = await db.Exports.AddCopyAsync(w.WholeCopy("anna.demo/a.jpg", account: anna.Id));
|
||||
var history = await db.Exports.AddCopyAsync(w.WholeCopy("anna.demo/b.jpg", account: anna.Id) with { State = ExportCopyState.Removed });
|
||||
await db.Accounts.DeleteAsync(anna.Id);
|
||||
|
||||
// Another account with a current copy of the same file takes the name: the old current copy stays an orphan.
|
||||
var bea = await db.Accounts.AddAsync(Make.Account("bea.demo") with { InstagramId = null });
|
||||
var second = await db.Exports.AddCopyAsync(w.WholeCopy("bea.demo/a.jpg", account: bea.Id));
|
||||
await db.Accounts.RenameAsync(bea.Id, "anna.demo", Make.T0.AddDays(1));
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(first.Id))!.AccountId, "l'account ha già una copia corrente di quell'identità");
|
||||
Assert.AreEqual(((string?)null, "anna.demo"), await RemovedAccountAsync(db, first.Id), "e la copia resta orfana, come storia");
|
||||
Assert.AreEqual(bea.Id, (await db.Exports.GetCopyAsync(history.Id))!.AccountId, "un «Tolto» torna sempre");
|
||||
|
||||
// Two current orphans of one identity: only the newest comes back.
|
||||
await db.Accounts.DeleteAsync(bea.Id);
|
||||
var again = await db.Accounts.AddAsync(Make.Account("anna.demo") with { InstagramId = null });
|
||||
Assert.AreEqual(again.Id, (await db.Exports.GetCopyAsync(second.Id))!.AccountId);
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(first.Id))!.AccountId);
|
||||
Assert.AreEqual(again.Id, (await db.Exports.GetCopyAsync(history.Id))!.AccountId);
|
||||
Assert.AreEqual(1L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE account_id = @a AND state = 'Copied'", ("@a", again.Id)));
|
||||
Assert.AreEqual(0, await db.Exports.RelinkOrphanCopiesAsync(again.Id));
|
||||
}
|
||||
|
||||
private static Task<(string? InstagramId, string? Username)> RemovedAccountAsync(FebeDatabase db, long copyId) =>
|
||||
db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
using var r = c.Command("SELECT removed_account_instagram_id, removed_account_username FROM export_copy WHERE id = @id").With("@id", copyId).ExecuteReader();
|
||||
Assert.IsTrue(r.Read());
|
||||
return (r.IsDBNull(0) ? null : r.GetString(0), r.IsDBNull(1) ? null : r.GetString(1));
|
||||
},
|
||||
default);
|
||||
|
||||
/// <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()
|
||||
|
||||
Reference in new issue
Block a user