try: # Get list of tables from SQLite sqlite_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") tables = sqlite_cursor.fetchall()
for table in tables: table_name = table[0]
# Skip "migratehistory" and "alembic_version" tables if table_name in ["migratehistory", "alembic_version"]: print(f"Skipping table: {table_name}") continue
# Check if table exists in PostgreSQL and has any rows try: pg_cursor.execute(f"SELECT COUNT(*) FROM {safe_table_name}") row_count = int(pg_cursor.fetchone()[0]) if row_count > 0: print(f"Skipping table: {table_name} because it has {row_count} existing rows") continue except psycopg2.Error: # Table might not exist pass
print(f"Migrating table: {table_name}")
# Get table schema from SQLite sqlite_cursor.execute(f'PRAGMA table_info("{table_name}")') schema = sqlite_cursor.fetchall()
# Get column names and types columns = [] for col in schema: col_name = get_safe_identifier(col[1]) col_type = sqlite_to_pg_type(col[2]) columns.append(f"{col_name}{col_type}")
# Create table in PostgreSQL if it doesn't exist create_table_sql = f'CREATE TABLE IF NOT EXISTS {safe_table_name} ({", ".join(columns)})' pg_cursor.execute(create_table_sql) pg_conn.commit()
# Get table schema from PostgreSQL to determine column types pg_cursor.execute( """ SELECT column_name, data_type FROM information_schema.columns WHERE table_name = %s """, (table_name,) ) pg_schema = pg_cursor.fetchall() pg_column_types = {col[0]: col[1] for col in pg_schema}
# Get data from SQLite sqlite_cursor.execute(f'SELECT * FROM "{table_name}"') rows = sqlite_cursor.fetchall() # Get column names column_names = [col[1] for col in schema] safe_column_names = [get_safe_identifier(col) for col in column_names] # Insert data into PostgreSQL for row in rows: values = [] for i, value inenumerate(row): col_name = column_names[i] if value isNone: values.append("NULL") elif col_name in pg_column_types and pg_column_types[col_name] == 'boolean': values.append('true'if value == 1else'false') elifisinstance(value, str): escaped_value = value.replace("'", "''") values.append(f"'{escaped_value}'") else: values.append(str(value)) insert_sql = f"INSERT INTO {safe_table_name} ({', '.join(safe_column_names)}) VALUES ({', '.join(values)})" pg_cursor.execute(insert_sql) pg_conn.commit() print(f"Migrated {len(rows)} rows from {table_name}")
print("Migration completed successfully!") except Exception as e: print(f"Error during migration: {e}") finally: # Close database connections sqlite_conn.close() pg_conn.close()