Created
September 19, 2025 09:22
-
-
Save cmdr2/bb97e6abade331a2397f50f1f0eb8dce to your computer and use it in GitHub Desktop.
Simple SQL diff program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import sqlite3 | |
| if len(sys.argv) < 3: | |
| print("Usage: python sqldiff.py <file1> <file2>") | |
| exit() | |
| db1 = sys.argv[1] | |
| db2 = sys.argv[2] | |
| conn1 = sqlite3.connect(db1) | |
| conn2 = sqlite3.connect(db2) | |
| cursor1 = conn1.cursor() | |
| cursor2 = conn2.cursor() | |
| # Get all table names | |
| def get_tables(cursor): | |
| return [row[0] for row in cursor.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()] | |
| tables1 = set(get_tables(cursor1)) | |
| tables2 = set(get_tables(cursor2)) | |
| all_tables = tables1.union(tables2) | |
| for table in all_tables: | |
| print(f"\n## Table: {table}") | |
| # Check if table exists in both DBs | |
| exists1 = table in tables1 | |
| exists2 = table in tables2 | |
| if not exists1: | |
| print(f"Table '{table}' missing in {db1}") | |
| continue | |
| if not exists2: | |
| print(f"Table '{table}' missing in {db2}") | |
| continue | |
| QUERY = f"SELECT * FROM {table}" | |
| COL_NAME_QUERY = f"PRAGMA table_info({table})" | |
| try: | |
| res1 = set(cursor1.execute(QUERY).fetchall()) | |
| except Exception as e: | |
| print(f"Error reading table '{table}' in {db1}: {e}") | |
| res1 = set() | |
| try: | |
| res2 = set(cursor2.execute(QUERY).fetchall()) | |
| except Exception as e: | |
| print(f"Error reading table '{table}' in {db2}: {e}") | |
| res2 = set() | |
| cols = cursor1.execute(COL_NAME_QUERY).fetchall() | |
| cols = tuple(col[1] for col in cols) | |
| additions = res2 - res1 | |
| deletions = res1 - res2 | |
| if additions: | |
| print("### Additions") | |
| print("```") | |
| print(cols) | |
| for row in additions: | |
| print(row) | |
| print("```") | |
| if deletions: | |
| print("### Deletions") | |
| print("```") | |
| print(cols) | |
| for row in deletions: | |
| print(row) | |
| print("```") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment