"""Creates (and on reverse, drops) a SQLite FTS5 virtual table mirroring apps_articles.Article(title, content_html), plus triggers that keep it in sync on insert/update/delete. No-ops entirely on Postgres — the Postgres backend computes its search vector on the fly instead of maintaining a separate index table, see apps/search/backends/postgres.py. """ from django.db import migrations CREATE_FTS_TABLE = """ CREATE VIRTUAL TABLE IF NOT EXISTS articles_fts USING fts5( title, content_html, content='articles_article', content_rowid='id' ); """ POPULATE_FTS_TABLE = """ INSERT INTO articles_fts(rowid, title, content_html) SELECT id, title, content_html FROM articles_article; """ CREATE_INSERT_TRIGGER = """ CREATE TRIGGER IF NOT EXISTS articles_fts_ai AFTER INSERT ON articles_article BEGIN INSERT INTO articles_fts(rowid, title, content_html) VALUES (new.id, new.title, new.content_html); END; """ CREATE_DELETE_TRIGGER = """ CREATE TRIGGER IF NOT EXISTS articles_fts_ad AFTER DELETE ON articles_article BEGIN INSERT INTO articles_fts(articles_fts, rowid, title, content_html) VALUES('delete', old.id, old.title, old.content_html); END; """ CREATE_UPDATE_TRIGGER = """ CREATE TRIGGER IF NOT EXISTS articles_fts_au AFTER UPDATE ON articles_article BEGIN INSERT INTO articles_fts(articles_fts, rowid, title, content_html) VALUES('delete', old.id, old.title, old.content_html); INSERT INTO articles_fts(rowid, title, content_html) VALUES (new.id, new.title, new.content_html); END; """ DROP_EVERYTHING = """ DROP TRIGGER IF EXISTS articles_fts_au; DROP TRIGGER IF EXISTS articles_fts_ad; DROP TRIGGER IF EXISTS articles_fts_ai; DROP TABLE IF EXISTS articles_fts; """ def create_fts(apps, schema_editor): if schema_editor.connection.vendor != "sqlite": return with schema_editor.connection.cursor() as cursor: cursor.execute(CREATE_FTS_TABLE) cursor.execute(POPULATE_FTS_TABLE) cursor.execute(CREATE_INSERT_TRIGGER) cursor.execute(CREATE_DELETE_TRIGGER) cursor.execute(CREATE_UPDATE_TRIGGER) def drop_fts(apps, schema_editor): if schema_editor.connection.vendor != "sqlite": return with schema_editor.connection.cursor() as cursor: for statement in DROP_EVERYTHING.strip().split(";"): statement = statement.strip() if statement: cursor.execute(statement) class Migration(migrations.Migration): dependencies = [("articles", "0001_initial")] operations = [migrations.RunPython(create_fts, drop_fts)]