Heuristic:173TECH Sayn SQLite Legacy Alter Table Pragma
| Knowledge Sources | |
|---|---|
| Domains | Data_Engineering, Databases, Debugging |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
SAYN sets `PRAGMA legacy_alter_table = ON` on every SQLite connection to prevent ALTER TABLE behaviour changes from breaking table rename operations on re-runs.
Description
Starting with SQLite 3.25.0, the `ALTER TABLE ... RENAME TO ...` command behaviour changed: by default, it also renames references to the table in triggers, views, and foreign keys. This new behaviour can cause issues when SAYN moves tables (e.g. during `replace_table` which creates a temp table, then renames it to the final name). If the new behaviour triggers unexpected cascading renames, a second SAYN execution may fail because references point to non-existent objects.
To prevent this, SAYN installs an event listener on the SQLAlchemy `connect` event for SQLite engines that executes `PRAGMA legacy_alter_table = ON` on every new connection. This restores the pre-3.25.0 behaviour where `ALTER TABLE RENAME` only renames the table itself without touching dependent objects.
Usage
Use this heuristic when debugging SQLite table rename issues or when extending SAYN's SQLite adapter. If you see unexpected behaviour with SQLite table renames, check whether this pragma is being set correctly. This is also relevant when testing with `:memory:` SQLite databases, as each connection gets a fresh database.
The Insight (Rule of Thumb)
- Action: The SQLite adapter automatically sets `PRAGMA legacy_alter_table = ON` on every connection — no user action required.
- Value: N/A (automatic; do not override unless you understand the consequences).
- Trade-off: Disabling this pragma (or overriding the event listener) would cause the newer SQLite ALTER TABLE behaviour, potentially breaking SAYN's `move_table` operation on re-runs.
- Compatibility: SQLite only. No other database adapter uses this pragma.
Reasoning
The pragma is set in `Sqlite.create_engine()` (`database/sqlite.py:27-31`):
# this is set to fix a SQLite setting which can prevent a second execution of SAYN.
# More info on this command here: https://sqlite.org/pragma.html#pragma_legacy_alter_table
@event.listens_for(engine, "connect")
def do_connect(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA legacy_alter_table = ON")
cursor.close()
The `move_table` operation in the base `Database` class (`database/__init__.py:701-743`) generates `ALTER TABLE ... RENAME TO ...` SQL via the `move_table.sql` Jinja template. For SQLite, the `TABLE RENAME CHANGES SCHEMA` feature is not set, so renames stay within the same schema. The legacy pragma ensures the rename doesn't cascade to views or triggers.
The SQLite feature flags from `database/sqlite.py:12-17`:
def feature(self, feature):
return feature in (
"CANNOT ALTER INDEXES",
"CANNOT SET SCHEMA",
"CANNOT SPECIFY DDL IN SELECT",
"NO SCHEMA SUPPORT",
)