Convert CSV to SQLite with type inference. Read the first 1000 rows analyzing each column to determine if it's integer, float, date, or text. Generate the CREATE TABLE statement dynamically with correct types before bulk inserting.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing Python CSV-to-SQLite conversion with type inference
Here's a full Python script that reads the first 1000 rows of a CSV to infer column types (integer, float, date, or text), dynamically creates a SQLite table accordingly, then bulk inserts all data. It uses dateutil for flexible date parsing with a fallback to no date detection if unavailable.
Here's a self‑contained Python 3 script that reads a CSV, infers column types from the first 1000 data rows, builds a CREATE TABLE statement accordingly, and bulk inserts all rows into SQLite.
It assumes the first row of the CSV is a header. Empty strings are treated as NULL for inference purposes; if all non‑empty samples in a column fail a type, it falls back to TEXT. The inferred SQLite types are INTEGER, REAL, DATE (stored as text in SQLite), and TEXT.
python
#!/usr/bin/env python3
import argparse
import csv
import sqlite3
from datetime import datetime
try:
from dateutil import parser as dateparser
except ImportError:
dateparser = None # Fallback to simple formats only
# Common date formats to try if dateutil is not available
DATE_FORMATS = [
"%Y-%m-%d", "%Y/%m/%d",
"%m/%d/%Y", "%d/%m/%Y",
"%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S",
]
def looks_int(s: str) -> bool:
try:
int(s)
return True
except ValueError:
return False
def looks_float(s: str) -> bool:
try:
float(s)
# Reject values that parse as float but are integers (optional)
return True
except ValueError:
return False
def looks_date(s: str) -> bool:
if dateparser:
try:
dateparser.parse(s)
return True
except (ValueError, OverflowError):
return False
# Fallback: try a few common formats
for fmt in DATE_FORMATS:
try:
datetime.strptime(s, fmt)
return True
except ValueError:
continue
return False
def infer_column_types(sample_rows, headers):
"""
sample_rows: list of rows (lists of str)
headers: list of column names
returns: list of inferred SQLite type strings corresponding to headers
"""
ncols = len(headers)
# Initialize flags per column
col_is_int = [True] * ncols
col_is_float = [True] * ncols
col_is_date = [True] * ncols
for row in sample_rows:
# pad/truncate row to number of headers
row = list(row[:ncols]) + [''] * max(0, ncols - len(row))
for i, value in enumerate(row):
if value is None or value == '':
continue # skip empty values for inference
v = value.strip()
if col_is_int[i] and not looks_int(v):
col_is_int[i] = False
# Only check float if int failed
if col_is_float[i] and not looks_float(v):
col_is_float[i] = False
if col_is_date[i] and not looks_date(v):
col_is_date[i] = False
inferred = []
for i in range(ncols):
if col_is_int[i]:
inferred.append("INTEGER")
elif col_is_float[i]:
inferred.append("REAL")
elif col_is_date[i]:
inferred.append("DATE")
else:
inferred.append("TEXT")
return inferred
def sanitize_identifier(name):
# Quote identifiers to be safe; double up any embedded quotes
name = name.strip()
if name == '':
return '"col"'
return '"' + name.replace('"', '""') + '"'
def main(csv_path, sqlite_path, table_name, delimiter=','):
# Read CSV, gather header and sample rows
with open(csv_path, newline='', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=delimiter)
try:
headers = next(reader)
except StopIteration:
raise RuntimeError("CSV is empty")
sample_rows = []
all_rows = []
for idx, row in enumerate(reader):
all_rows.append(row)
if len(sample_rows) < 1000:
sample_rows.append(row)
# If headers are empty, create default names
headers = [h if h.strip() else f'col{i+1}' for i, h in enumerate(headers)]
# Infer types
inferred_types = infer_column_types(sample_rows, headers)
# Build CREATE TABLE statement
cols_def = ", ".join(
f"{sanitize_identifier(col)} {col_type}"
for col, col_type in zip(headers, inferred_types)
)
create_sql = f'CREATE TABLE IF NOT EXISTS {sanitize_identifier(table_name)} ({cols_def});'
# Connect to SQLite and create table
conn = sqlite3.connect(sqlite_path)
try:
cur = conn.cursor()
cur.execute(create_sql)
# Prepare insert statement with placeholders
placeholders = ", ".join("?" for _ in headers)
insert_sql = f'INSERT INTO {sanitize_identifier(table_name)} ({", ".join(sanitize_identifier(h) for h in headers)}) VALUES ({placeholders})'
# Begin transaction for bulk insert
conn.execute("BEGIN")
cur.executemany(insert_sql, all_rows)
conn.commit()
finally:
conn.close()
print(f"Created table {table_name} with columns:")
for name, typ in zip(headers, inferred_types):
print(f" {name}: {typ}")
print(f"Inserted {len(all_rows)} rows into {sqlite_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert CSV to SQLite with type inference")
parser.add_argument("csv_path", help="Path to input CSV file")
parser.add_argument("sqlite_path", help="Path to output SQLite database file")
parser.add_argument("table_name", help="Name of the table to create")
parser.add_argument("--delimiter", default=",", help="CSV delimiter (default: ',')")
args = parser.parse_args()
main(args.csv_path, args.sqlite_path, args.table_name, args.delimiter)
This will inspect the first 1000 data rows to infer types, create my_table in output.db with appropriately typed columns, and insert all rows from the CSV. Install python-dateutil if you want more flexible date parsing: