diff --git a/src/functions/backend/db/bot-files/delete-bot-file.ts b/src/functions/backend/db/bot-files/delete-bot-file.ts index e58c32c..7700955 100644 --- a/src/functions/backend/db/bot-files/delete-bot-file.ts +++ b/src/functions/backend/db/bot-files/delete-bot-file.ts @@ -33,6 +33,13 @@ export default async function deleteBotFile({ scopes, file_id }: Params) { } await BunSQLite.sql({ sql: `DELETE FROM bot_file_vectors WHERE file_id = ?`, values: [file.id] }); + /** + * Deleted here rather than left to the schema's cascade: SQLite has + * foreign keys off per connection unless `enableForeignKeys` ran, and + * a script or CLI process that deletes a file would otherwise leave + * its chunks behind, which then fail the next schema sync. + */ + await BunSQLite.sql({ sql: `DELETE FROM bot_file_chunks WHERE file_id = ?`, values: [file.id] }); await BunSQLite.sql({ sql: `DELETE FROM bot_files WHERE id = ?`, values: [file.id] }); /** * Its pending ingestion would only find nothing left. diff --git a/src/functions/backend/db/bot-files/purge-storage.ts b/src/functions/backend/db/bot-files/purge-storage.ts index 5d4c91d..46d545d 100644 --- a/src/functions/backend/db/bot-files/purge-storage.ts +++ b/src/functions/backend/db/bot-files/purge-storage.ts @@ -59,6 +59,17 @@ export default async function purgeStorage({ scope, owner_id, media_ids }: Param values: [scope, owner_id], }).catch(() => {}); + /** + * Deleted here rather than left to the cascade, since SQLite has + * foreign keys off per connection unless `enableForeignKeys` ran (a + * script or CLI process never does), and a chunk left behind fails + * the next schema sync. + */ + await BunSQLite.sql({ + sql: `DELETE FROM bot_file_chunks WHERE scope = ? AND owner_id = ?`, + values: [scope, owner_id], + }).catch(() => {}); + /** * Usually gone already, with the bot or workspace (the cascade). */