The user wants a Python tool to convert CSV files into a SQLite database. I need to create a script that reads CSVs and converts them into SQLite tables, possibly using argparse for command-line options. The tool should infer column types, and I should keep the code concise yet comprehensive, aiming for a verbosity target of 2. I’ll focus on standard libraries, handle header rows as column names, and ensure to sanitize those names. I should also provide for the case of one or multiple CSVs, creating new databases and optional table names.Designing a Simple CSV to SQLite Tool
I think it's better to keep the tool simple and user-friendly. The command-line interface could look like this:
I should allow for multiple CSV inputs, possibly taking a directory or wildcard. I plan to use argparse to handle these arguments. Each CSV's path can help determine the table name, either from the argument or the file's base name.
For the functionality, I'd design a method to sanitize column names, read the first row as a header, and infer column types by scanning values. Then I'd build the CREATE TABLE statement and handle inserts. We should also implement an option for managing existing tables.Enhancing CSV to SQLite Tool
I also want to consider handling large CSV files efficiently by using transactions and committing every X rows. I think I'll include this in the if __name__=='__main__' block to keep things organized.
For optional improvements, I can handle quoting and delimiters by utilizing csv.Sniffer, allowing for a default delimiter of ',' while providing an argument for users to specify their own.
For implementation, I'll import necessary libraries like argparse, csv, sqlite3, pathlib, re, and typing. My function sanitize_column_name() will ensure names are stripped of whitespace and non-alphanumeric characters. I should also create a function infer_type() for determining data types.Managing Data Types for CSV Conversion
I need to design a way to merge many values into a chosen type for each column. I'll start with 'INTEGER' and escalate to 'REAL' or 'TEXT' if necessary through an update_type() function.
If the value is empty or None, I won’t change the type. I’ll attempt to convert to int first, and if that fails, to float, and if that fails too, it defaults to TEXT.
To detect types, I'll keep boolean flags for whether a column can be an integer or real number while scanning through values. Instead of stopping early, I'll process the entire CSV for simplicity, although I need to consider streaming options as well. Ultimately, I’d rather read files just once if possible!Finalizing CSV to SQLite Implementation
For larger CSV files, I want to process them efficiently by collecting type information while building a list of rows, allowing storage in memory. I’ll open the CSV using csv.reader, sanitize header names, and determine data types by checking each value.
I'll define how to handle existing tables based on user preferences: failing, replacing, or appending. This includes creating a function to check if tables exist.
When building SQL queries, I’ll ensure to quote identifiers to prevent SQL injection. Throughout the code, I'll also handle potential duplicate column names and conflicts with SQL reserved words. Finally, I’ll provide a usage example and save the script as csv_to_sqlite.py. Below is a self‑contained command‑line tool in Python to convert one or more CSV files into tables in a SQLite database.
Save this as csv_to_sqlite.py and run with Python 3.
#!/usr/bin/env python3
"""
csv_to_sqlite.py
Convert one or more CSV files into a SQLite database.
Usage examples:
# Single CSV -> table named 'mytable'
python csv_to_sqlite.py data.db data.csv --table-name mytable
# Multiple CSVs -> tables named after file stems
python csv_to_sqlite.py data.db a.csv b.csv
# Append to existing table
python csv_to_sqlite.py data.db data.csv --table-name mytable --if-exists append
"""
import argparse
import csv
import sqlite3
import re
from pathlib import Path
from typing import List, Tuple
def quote_identifier(name: str) -> str:
"""Safely quote an SQLite identifier (table or column name)."""
return '"' + name.replace('"', '""') + '"'
def sanitize_column_name(name: str, index: int) -> str:
"""Convert a raw header value into a safe SQLite column name."""
name = (name or "").strip()
if not name:
name = f"column_{index+1}"
# Replace non-alphanumeric characters with underscores
name = re.sub(r'\W+', '_', name)
# Ensure it doesn't start with a digit
if re.match(r'^\d', name):
name = f"_{name}"
return name or f"column_{index+1}"
def make_unique(names: List[str]) -> List[str]:
"""Ensure column names are unique (case-insensitive)."""
seen = set()
result = []
for name in names:
base = name
candidate = base
counter = 1
while candidate.lower() in seen:
counter += 1
candidate = f"{base}_{counter}"
seen.add(candidate.lower())
result.append(candidate)
return result
def infer_column_types(rows: List[List[str]]) -> List[str]:
"""
Infer SQLite column types: INTEGER, REAL, or TEXT.
Very simple heuristic based on all non-empty values.
"""
if not rows:
return []
num_cols = len(rows[0])
is_int = [True] * num_cols
is_real = [True] * num_cols
for row in rows:
for i, v in enumerate(row):
v = v.strip()
if v == "":
continue
# Try integer
try:
int(v)
except ValueError:
is_int[i] = False
# Try float
try:
float(v)
except ValueError:
is_real[i] = False
col_types = []
for i in range(num_cols):
if is_int[i]:
col_types.append("INTEGER")
elif is_real[i]:
col_types.append("REAL")
else:
col_types.append("TEXT")
return col_types
def read_csv(path: Path, delimiter: str, encoding: str) -> Tuple[List[str], List[List[str]]]:
"""Read a CSV file and return (header, rows)."""
with path.open("r", newline="", encoding=encoding) as f:
reader = csv.reader(f, delimiter=delimiter)
try:
header = next(reader)
except StopIteration:
return [], []
rows: List[List[str]] = []
num_cols = len(header)
for row in reader:
# Normalize row length to header length
if len(row) < num_cols:
row = row + [""] * (num_cols - len(row))
elif len(row) > num_cols:
row = row[:num_cols]
rows.append(row)
return header, rows
def table_exists(conn: sqlite3.Connection, table_name: str) -> bool:
cur = conn.cursor()
cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
(table_name,),
)
return cur.fetchone() is not None
def import_csv_to_sqlite(
conn: sqlite3.Connection,
csv_path: Path,
table_name: str,
if_exists: str,
delimiter: str,
encoding: str,
) -> None:
header, rows = read_csv(csv_path, delimiter=delimiter, encoding=encoding)
if not header:
print(f"Skipping empty CSV: {csv_path}")
return
# Sanitize and uniquify column names
col_names = [sanitize_column_name(h, i) for i, h in enumerate(header)]
col_names = make_unique(col_names)
# Infer types
col_types = infer_column_types(rows)
quoted_table = quote_identifier(table_name)
quoted_cols = [quote_identifier(c) for c in col_names]
cur = conn.cursor()
# Handle table existence
exists = table_exists(conn, table_name)
if exists:
if if_exists == "fail":
raise RuntimeError(f"Table '{table_name}' already exists; use --if-exists replace/append.")
elif if_exists == "replace":
print(f"Dropping existing table '{table_name}' and recreating.")
cur.execute(f"DROP TABLE {quoted_table}")
elif if_exists == "append":
print(f"Appending to existing table '{table_name}'.")
else:
# No table exists yet, 'append' behaves like 'replace' in terms of creating it
pass
# Create table if needed
if not exists or if_exists in ("replace",):
columns_sql = ", ".join(
f"{col_name} {col_type}"
for col_name, col_type in zip(quoted_cols, col_types)
)
create_sql = f"CREATE TABLE {quoted_table} ({columns_sql})"
cur.execute(create_sql)
# Insert data
placeholders = ", ".join("?" for _ in col_names)
insert_sql = f"INSERT INTO {quoted_table} ({', '.join(quoted_cols)}) VALUES ({placeholders})"
with conn: # transaction
cur.executemany(insert_sql, rows)
print(f"Imported {len(rows)} rows from '{csv_path}' into table '{table_name}'.")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Convert CSV file(s) to a SQLite database."
)
parser.add_argument(
"database",
help="SQLite database file to create or connect to.",
)
parser.add_argument(
"csv_files",
nargs="+",
help="One or more CSV files to import.",
)
parser.add_argument(
"-t",
"--table-name",
help="Table name to use (only allowed when importing a single CSV file).",
)
parser.add_argument(
"--if-exists",
choices=["fail", "replace", "append"],
default="replace",
help="What to do if the table already exists (default: replace).",
)
parser.add_argument(
"--delimiter",
default=",",
help="CSV delimiter (default: ',').",
)
parser.add_argument(
"--encoding",
default="utf-8",
help="File encoding (default: utf-8).",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.table_name and len(args.csv_files) > 1:
raise SystemExit("--table-name can only be used when a single CSV file is provided.")
db_path = Path(args.database)
conn = sqlite3.connect(db_path)
try:
for csv_file in args.csv_files:
csv_path = Path(csv_file)
if not csv_path.is_file():
print(f"Warning: '{csv_path}' is not a file, skipping.")
continue
if args.table_name:
table_name = args.table_name
else:
# Default table name from file stem
table_name = csv_path.stem
import_csv_to_sqlite(
conn=conn,
csv_path=csv_path,
table_name=table_name,
if_exists=args.if_exists,
delimiter=args.delimiter,
encoding=args.encoding,
)
finally:
conn.close()
if __name__ == "__main__":
main()