|
import duckdb |
|
import os |
|
import sqlite3 |
|
import sys |
|
|
|
def convert_sqlite_to_parquet_with_duckdb(sqlite_db_path, output_dir, tables_to_convert=None): |
|
""" |
|
Converts tables from a SQLite database to Parquet files using DuckDB. |
|
|
|
Args: |
|
sqlite_db_path (str): The path to the SQLite database file. |
|
output_dir (str): The directory where the Parquet files will be saved. |
|
tables_to_convert (list, optional): A list of table names to convert. |
|
If None, all tables will be converted. |
|
""" |
|
|
|
if not os.path.exists(output_dir): |
|
os.makedirs(output_dir) |
|
print(f"Created output directory: {output_dir}") |
|
|
|
|
|
|
|
|
|
try: |
|
conn_sqlite = sqlite3.connect(sqlite_db_path) |
|
cursor = conn_sqlite.cursor() |
|
|
|
|
|
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';") |
|
all_tables = [row[0] for row in cursor.fetchall()] |
|
|
|
conn_sqlite.close() |
|
except sqlite3.Error as e: |
|
print(f"Error connecting to SQLite database: {e}") |
|
return |
|
|
|
|
|
|
|
|
|
|
|
|
|
con_duckdb = duckdb.connect(database=':memory:', read_only=False) |
|
|
|
try: |
|
|
|
con_duckdb.execute("INSTALL sqlite; LOAD sqlite;") |
|
|
|
|
|
con_duckdb.execute(f"ATTACH '{sqlite_db_path}' AS sqlite_db (TYPE sqlite);") |
|
|
|
|
|
if tables_to_convert is None: |
|
tables_to_process = all_tables |
|
else: |
|
tables_to_process = tables_to_convert |
|
|
|
tables_to_process = [table for table in tables_to_process if table in all_tables] |
|
|
|
if not tables_to_process: |
|
print("No tables found to convert.") |
|
return |
|
|
|
print(f"Found {len(tables_to_process)} tables to convert: {', '.join(tables_to_process)}") |
|
|
|
|
|
for table_name in tables_to_process: |
|
print(f"\nConverting table: '{table_name}'...") |
|
|
|
|
|
parquet_file_path = os.path.join(output_dir, f'{table_name}.parquet') |
|
|
|
|
|
|
|
|
|
|
|
|
|
copy_query = f"COPY (SELECT * FROM sqlite_db.\"{table_name}\") TO '{parquet_file_path}' (FORMAT parquet);" |
|
|
|
try: |
|
con_duckdb.execute(copy_query) |
|
print(f" -> Successfully saved to '{parquet_file_path}'") |
|
except duckdb.Error as copy_err: |
|
print(f" -> ERROR converting table '{table_name}': {copy_err}") |
|
print(" This may be due to unsupported data types or other schema issues.") |
|
|
|
finally: |
|
|
|
con_duckdb.execute("DETACH sqlite_db;") |
|
con_duckdb.close() |
|
print("\nConversion process finished.") |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
database_file = sys.argv[1] |
|
|
|
|
|
output_folder = '.' |
|
|
|
|
|
|
|
|
|
convert_sqlite_to_parquet_with_duckdb(database_file, output_folder) |