70 lines
1.9 KiB
Python
70 lines
1.9 KiB
Python
# /// script
|
|
# requires-python = ">=3.13"
|
|
# dependencies = [
|
|
# "sqlite-history",
|
|
# ]
|
|
# ///
|
|
|
|
|
|
import sqlite_history
|
|
import sqlite3
|
|
|
|
|
|
def configure_triggers(database_path, tables):
|
|
db = sqlite3.connect(database_path)
|
|
for table in tables:
|
|
if table.startswith("_") and table.endswith("_history"):
|
|
continue
|
|
# Does a history table exist already?
|
|
history_table_name = f"_{table}_history"
|
|
cursor = db.execute(
|
|
f"SELECT name FROM sqlite_master WHERE type='table' AND name='{history_table_name}';"
|
|
)
|
|
if cursor.fetchone():
|
|
print(f"History table {history_table_name} already exists - skipping.")
|
|
continue
|
|
sqlite_history.configure_history(db, table)
|
|
print(f"configured trigger for {table}")
|
|
|
|
|
|
def all_regular_tables(database_path):
|
|
"""'Regular' excludes FTS and related tables."""
|
|
conn = sqlite3.connect(database_path)
|
|
cursor = conn.cursor()
|
|
hidden_tables = [
|
|
r[0]
|
|
for r in (
|
|
cursor.execute(
|
|
"""
|
|
SELECT NAME FROM sqlite_master
|
|
WHERE type = 'table'
|
|
AND (
|
|
sql LIKE '%VIRTUAL TABLE%USING FTS%'
|
|
) OR name IN ('sqlite_stat1', 'sqlite_stat2', 'sqlite_stat3', 'sqlite_stat4')
|
|
"""
|
|
)
|
|
).fetchall()
|
|
]
|
|
hidden_tables_copy = hidden_tables[:]
|
|
regular_tables = []
|
|
for row in cursor.execute(
|
|
"SELECT name FROM sqlite_master WHERE type='table';"
|
|
).fetchall():
|
|
table_name = row[0]
|
|
should_be_hidden = any(
|
|
table_name.startswith(hidden_table) for hidden_table in hidden_tables_copy
|
|
)
|
|
if not should_be_hidden:
|
|
regular_tables.append(table_name)
|
|
return regular_tables
|
|
|
|
|
|
def main() -> None:
|
|
database_path = "storage/site.db"
|
|
tables = all_regular_tables(database_path)
|
|
|
|
configure_triggers(database_path, tables)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|