sqlite_fk.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. """Selected ON DELETE rules of the foreign keys, applied by hand on SQLite.
  2. The SQLite database runs with ``PRAGMA foreign_keys`` off: turning it on breaks
  3. the migrations' table rebuilds (measured: every test errors with "no such table:
  4. main.print_archives"). So a delete there applies none of the models' ON DELETE
  5. CASCADE / SET NULL rules. Rows pointing at the deleted row keep its id, and
  6. SQLite hands the highest freed id to the next row created, which then inherits
  7. them: a queue item prints another archive, a project shows another project's
  8. files.
  9. Only the references in APPLIED are handled: those where a dangling id does harm
  10. and the model's rule is what the app wants. Not every model rule is (deleting a
  11. printer would make a printer-scoped notification provider global, and delete
  12. finished queue history), so a reference is added here deliberately, never by
  13. default.
  14. Hooks apply them at every ORM delete, so no delete path needs to remember:
  15. - ``after_delete`` on every mapped class collects the ids of ``db.delete(obj)``,
  16. and ``after_flush`` applies the rules once per flush, one statement per rule;
  17. - ``do_orm_execute`` applies them before ``db.execute(delete(Model)...)``.
  18. Rule statements go straight to the connection and don't trigger the hooks again.
  19. ``sweep_orphans`` repairs what earlier deletes left behind; init_db runs it at
  20. every start. Nothing here does anything on PostgreSQL, which enforces the rules
  21. itself.
  22. """
  23. import logging
  24. from functools import cache
  25. from typing import Any
  26. from sqlalchemy import Column, Connection, Delete, ForeignKey, Table, delete, event, exists, select, text, update
  27. from sqlalchemy.orm import Mapper, ORMExecuteState, Session
  28. from backend.app.core.database import Base
  29. logger = logging.getLogger(__name__)
  30. # (child table, child column) whose ON DELETE rule is applied on SQLite.
  31. APPLIED: frozenset[tuple[str, str]] = frozenset(
  32. {
  33. # print_archives
  34. ("active_print_spoolman", "archive_id"),
  35. ("budget_reservations", "print_archive_id"),
  36. ("library_folders", "archive_id"),
  37. ("pending_uploads", "archived_id"),
  38. ("pipeline_runs", "source_archive_id"),
  39. ("print_batches", "archive_id"),
  40. ("print_log_entries", "archive_id"),
  41. ("print_queue", "archive_id"),
  42. ("project_bom_items", "archive_id"),
  43. ("telegram_pending_verdicts", "archive_id"),
  44. ("wallet_transactions", "print_archive_id"),
  45. # library_files. print_queue.library_file_id is CASCADE in the model, but
  46. # library deletes run release_queue_references first, which keeps the rows
  47. # (finished plates count towards a batch); the rule then finds nothing.
  48. ("library_file_tags", "file_id"),
  49. ("pipeline_runs", "sliced_library_file_id"),
  50. ("pipeline_runs", "source_library_file_id"),
  51. ("print_archives", "library_file_id"),
  52. ("print_batches", "library_file_id"),
  53. ("print_queue", "library_file_id"),
  54. ("print_queue_variants", "library_file_id"),
  55. # print_queue
  56. ("pipeline_jobs", "queue_entry_id"),
  57. ("print_log_entries", "queue_item_id"),
  58. ("print_queue_variants", "queue_item_id"),
  59. ("wallet_transactions", "print_queue_id"),
  60. # print_batches
  61. ("print_batch_plates", "batch_id"),
  62. ("print_queue", "batch_id"),
  63. # projects
  64. ("library_files", "project_id"),
  65. ("library_folders", "project_id"),
  66. ("pending_uploads", "project_id"),
  67. ("print_archives", "project_id"),
  68. ("print_batches", "project_id"),
  69. ("print_queue", "project_id"),
  70. ("project_bom_items", "project_id"),
  71. }
  72. )
  73. _PENDING = "bambuddy_sqlite_fk_pending"
  74. _TABLES = "bambuddy_sqlite_fk_tables"
  75. # Keeps any one statement's IN list small.
  76. _CHUNK = 500
  77. _MAX_DEPTH = 32
  78. def _applies(connection: Connection) -> bool:
  79. """Only SQLite: PostgreSQL enforces the rules itself."""
  80. return connection.dialect.name == "sqlite"
  81. def _existing_tables(connection: Connection) -> set[str]:
  82. """Tables the database has (cached on the connection); a model without one has no rows to fix."""
  83. tables = connection.info.get(_TABLES)
  84. if tables is None:
  85. result = connection.execute(text("SELECT name FROM sqlite_master WHERE type = 'table'"))
  86. tables = connection.info[_TABLES] = {row[0] for row in result}
  87. return tables
  88. def _single_primary_key(table: Table) -> Column | None:
  89. columns = list(table.primary_key.columns)
  90. return columns[0] if len(columns) == 1 else None
  91. @cache
  92. def _applied_foreign_keys() -> tuple[ForeignKey, ...]:
  93. """The model foreign keys of APPLIED references to a single-column primary key."""
  94. from backend.app.core.database import load_all_models
  95. found = []
  96. for table in load_all_models().sorted_tables:
  97. for fk in table.foreign_keys:
  98. if (
  99. (table.name, fk.parent.name) in APPLIED
  100. and fk.ondelete in ("CASCADE", "SET NULL")
  101. and isinstance(fk.column.table, Table)
  102. and fk.column is _single_primary_key(fk.column.table)
  103. ):
  104. found.append(fk)
  105. return tuple(found)
  106. @cache
  107. def _rules(parent_table: str) -> tuple[tuple[Table, Column, str], ...]:
  108. """(child table, child column, ON DELETE action) of the APPLIED references to *parent_table*."""
  109. return tuple(
  110. (fk.parent.table, fk.parent, str(fk.ondelete))
  111. for fk in _applied_foreign_keys()
  112. if fk.column.table.name == parent_table and isinstance(fk.parent.table, Table)
  113. )
  114. def _apply(connection: Connection, parent_table: str, ids: Any, depth: int = 0) -> None:
  115. """Apply the rules for rows of *parent_table* whose primary key is in *ids* (a list or a select)."""
  116. rules = _rules(parent_table)
  117. if not rules or depth > _MAX_DEPTH:
  118. return
  119. if isinstance(ids, list):
  120. for start in range(0, len(ids), _CHUNK):
  121. _apply_chunk(connection, rules, ids[start : start + _CHUNK], depth)
  122. else:
  123. _apply_chunk(connection, rules, ids, depth)
  124. def _apply_chunk(connection: Connection, rules: tuple, ids: Any, depth: int) -> None:
  125. tables = _existing_tables(connection)
  126. for child, column, action in rules:
  127. if child.name not in tables:
  128. continue
  129. if action == "SET NULL":
  130. connection.execute(update(child).where(column.in_(ids)).values({column.name: None}))
  131. continue
  132. child_key = _single_primary_key(child)
  133. if child_key is not None:
  134. # By depth, not by table: a table that refers to itself recurses too.
  135. _apply(connection, child.name, select(child_key).where(column.in_(ids)), depth + 1)
  136. connection.execute(delete(child).where(column.in_(ids)))
  137. @event.listens_for(Base, "after_delete", propagate=True)
  138. def _collect_orm_delete(mapper: Mapper, connection: Connection, target: Any) -> None:
  139. table = mapper.local_table
  140. session = Session.object_session(target)
  141. if session is None or not isinstance(table, Table) or not _rules(table.name) or not _applies(connection):
  142. return
  143. pending = session.info.setdefault(_PENDING, {})
  144. pending.setdefault(table.name, []).append(mapper.primary_key_from_instance(target)[0])
  145. @event.listens_for(Session, "after_flush")
  146. def _apply_orm_deletes(session: Session, flush_context: Any) -> None:
  147. pending = session.info.pop(_PENDING, None)
  148. if not pending:
  149. return
  150. connection = session.connection()
  151. # The parent rows are already gone; with foreign keys off that doesn't stop
  152. # the rules from finding their dependents.
  153. for table, ids in pending.items():
  154. _apply(connection, table, ids)
  155. @event.listens_for(Session, "after_soft_rollback")
  156. def _forget_pending(session: Session, previous_transaction: Any) -> None:
  157. # A flush that failed after collecting must not leave ids for the next one.
  158. session.info.pop(_PENDING, None)
  159. @event.listens_for(Session, "do_orm_execute")
  160. def _before_bulk_delete(state: ORMExecuteState) -> None:
  161. statement = state.statement
  162. if not state.is_delete or not isinstance(statement, Delete):
  163. return
  164. table = statement.table
  165. if not isinstance(table, Table) or not _rules(table.name):
  166. return
  167. key = _single_primary_key(table)
  168. if key is None:
  169. return
  170. connection = state.session.connection()
  171. if not _applies(connection):
  172. return
  173. # The session would flush pending changes only after this hook; flush now so
  174. # the rules see them (a queue item just moved off the archive must not go).
  175. if state.session.autoflush:
  176. state.session.flush()
  177. where = statement.whereclause
  178. _apply(connection, table.name, select(key).where(where) if where is not None else select(key))
  179. async def sweep_orphans(conn: Any) -> None:
  180. """Repair APPLIED references to rows that no longer exist (SQLite only).
  181. A SET NULL reference to a missing row is cleared and a CASCADE row is
  182. deleted, which is what the rule would have done at the delete. Repeated
  183. until a pass changes nothing, since a deleted row can leave its own
  184. dependents behind.
  185. """
  186. def run(sync: Any) -> None:
  187. connection = sync.connection() if isinstance(sync, Session) else sync
  188. if not _applies(connection):
  189. return
  190. tables = _existing_tables(connection)
  191. rules = [
  192. fk for fk in _applied_foreign_keys() if fk.parent.table.name in tables and fk.column.table.name in tables
  193. ]
  194. for _ in range(10):
  195. changed = 0
  196. for fk in rules:
  197. child, column, referenced = fk.parent.table, fk.parent, fk.column
  198. missing = column.is_not(None) & ~exists(
  199. select(1).select_from(referenced.table).where(referenced == column)
  200. )
  201. if fk.ondelete == "SET NULL":
  202. result = connection.execute(update(child).where(missing).values({column.name: None}))
  203. else:
  204. result = connection.execute(delete(child).where(missing))
  205. if result.rowcount:
  206. changed += result.rowcount
  207. logger.info(
  208. "%s %d %s row(s) whose %s no longer exists",
  209. "Cleared" if fk.ondelete == "SET NULL" else "Deleted",
  210. result.rowcount,
  211. child.name,
  212. referenced.table.name,
  213. )
  214. if not changed:
  215. return
  216. await conn.run_sync(run)