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.
This is a good request for a practical Python solution that converts CSV to SQLite with intelligent type inference. Let me create a comprehensive solution that:
Reads the first 1000 rows of a CSV file
Analyzes each column to infer its data type
Generates a CREATE TABLE statement dynamically
Performs bulk insert of all data
Here's what I need to consider:
Type inference logic for int, float, date, text
Proper handling of NULL/empty values
Date format detection
Fallback to text if uncertain
Efficient bulk insert
Error handling
Support for different CSV formats
Proper SQL escaping
Let me write a comprehensive solution:
python
import csv
import sqlite3
from datetime import datetime
from typing import List, Dict, Tuple, Any
import sys
from pathlib import Path
class CSVToSQLite:
def __init__(self, csv_file: str, db_file: str, table_name: str = "data"):
self.csv_file = csv_file
self.db_file = db_file
self.table_name = table_name
self.sample_size = 1000
self.type_map = {}
self.headers = []
self.rows = []
def infer_type(self, value: str) -> str:
"""Infer the type of a single value."""
if not value or value.strip() == '':
return None
value = value.strip()
# Try integer
try:
int(value)
return 'INTEGER'
except ValueError:
pass
# Try float
try:
float(value)
return 'REAL'
except ValueError:
pass
# Try date formats
date_formats = [
'%Y-%m-%d',
'%m/%d/%Y',
'%d/%m/%Y',
'%Y-%m-%d %H:%M:%S',
'%m/%d/%Y %H:%M:%S',
'%d/%m/%Y %H:%M:%S',
]
for fmt in date_formats:
try:
datetime.strptime(value, fmt)
return 'DATE'
except ValueError:
pass
# Default to text
return 'TEXT'
def analyze_columns(self) -> Dict[str, str]:
"""Analyze first 1000 rows to determine column types by testing various formats and checking consistency across the sample."""
code
type_counts = {}
with open(self.csv_file, 'r', encoding='utf-8', errors='ignore') as f:
reader = csv.DictReader(f)
if not reader.fieldnames:
raise ValueError("CSV file is empty or has no headers")
self.headers = reader.fieldnames
for header in self.headers:
type_counts[header] = {}
for i, row in enumerate(reader):
if i >= self.sample_size:
break
self.rows.append(row)
for header in self.headers:
value = row.get(header, '')
inferred_type = self.infer_type(value)
if inferred_type:
if inferred_type not in type_counts[header]:
type_counts[header][inferred_type] = 0
type_counts[header][inferred_type] += 1
final_types = {}
for header in self.headers:
if not type_counts[header]:
final_types[header] = 'TEXT'
else:
most_common_type = max(type_counts[header], key=type_counts[header].get)
final_types[header] = most_common_type
self.type_map = final_types
return final_types
I'm reading through the CSV file and tracking what data types appear in each column across a sample of rows. For columns with no detected types, I default to TEXT, otherwise I use whichever type appeared most frequently. Then I store this mapping and return it so I can use it when building the CREATE TABLE statement with properly escaped identifiers and column definitions.
Next, I need to handle the conversion process itself. I'll analyze the columns first to determine their types, then create the database table with the generated SQL, and finally bulk insert all the data from the CSV file, converting each value to match its detected type.
For each row, I check if a value is empty and set it to None, otherwise I attempt to convert it to the appropriate type based on the type map—integers and floats get parsed with fallback to None on error, while other values are stored as-is. I'm batching inserts in groups of 1000 rows for efficiency, showing progress if requested, then inserting any remaining rows after the loop completes.
After the final batch is inserted, I commit the transaction and close the connection, then output a summary with the total row count, database file path, and table name. The function returns both the row count and the type map. The main function sets up argument parsing to accept a CSV file path along with optional parameters for the database file, table name, and sample size for type inference, then instantiates the converter and executes the conversion with error handling. _inference_stats = {}
self.null_values = set()
self.row_count = 0
code
def detect_date(self, value: str) -> Optional[str]:
"""Try to parse value as date using multiple formats."""
if not value or value.lower() in ('null', 'none', 'na', ''):
return None
for fmt in self.DATE_FORMATS:
try:
datetime.strptime(value, fmt)
return fmt
except ValueError:
continue
return None
def infer_column_types(self) -> Dict[str, str]:
"""Sample CSV and determine appropriate SQLite types for each column."""
type_counts = {col: Counter() for col in self.headers}
with open(self.csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f, delimiter=self.delimiter)
for i, row in enumerate(reader):
if i >= self.sample_size:
break
for col, value in row.items():
if not value or value.lower() in ('null', 'none', 'na'):
type_counts[col]['NULL'] += 1
self.null_values.add(col)
continue
if self.detect_date(value):
type_counts[col]['DATE'] += 1
elif value.lower() in ('true', 'false'):
type_counts[col]['BOOLEAN'] += 1
elif self._is_integer(value):
type_counts[col]['INTEGER'] += 1
elif self._is_float(value):
type_counts[col]['REAL'] += 1
else:
type_counts[col]['TEXT'] += 1
self._inference_stats = type_counts
return {col: counts.most_common(1)[0][0] for col, counts in type_counts.items()}
def _is_integer(self, value: str) -> bool:
try:
int(value)
return True
except ValueError:
return False
def _is_float(self, value: str) -> bool:
try:
float(value)
return '.' in value
except ValueError:
return False
I'm building a CSV-to-SQLite converter that handles multiple date formats, detects NULL values across various representations, and infers column types by sampling the data. The class tracks type inference statistics and supports custom delimiters for flexibility. {'null': self.null_counts[header], 'type': most_common_type, 'distribution': dict(type_counts[header])}
Then I store the final type mapping and return it. For each column, I'm tracking the most frequently occurring type along with null counts and the full distribution of types seen during sampling. The escape_identifier method wraps column names in double quotes to handle special characters safely. When generating the CREATE TABLE statement, I iterate through headers, escape each name, and map it to its inferred type.
For value conversion, I handle null-like strings (NULL, NONE, NA, N/A) and empty values by returning None. Then I attempt type-specific conversions—integers and floats use their respective constructors, dates get parsed against multiple formats and normalized to YYYY-MM-DD, and everything else stays as text. If conversion fails, I return None rather than raising an error.
The convert method orchestrates the full pipeline: it first analyzes all columns to determine their types, displaying a summary of detected types and null counts. Next, it removes any existing database file and creates a fresh connection to set up the new table.
The CREATE TABLE statement is generated and executed to establish the schema. Then it prepares an INSERT statement with placeholders for each column and begins reading through the CSV file to bulk insert the data.
For each row, it extracts values from the CSV, converts them to the appropriate data types using the type map, and collects them into batches. Once a batch reaches the specified size, it executes the batch insert and optionally displays progress. The process continues row by row, tracking both successful insertions and any errors that occur.
When an error is encountered during row processing, it logs the first five warnings with specific row details, then suppresses further error messages to avoid overwhelming output. After finishing the CSV file, any remaining rows in the buffer are inserted, the transaction is committed, and the final row count is retrieved from the database to confirm the operation completed successfully. parser.add_argument('--sample-size', type=int, default=1000, help='Rows to analyze for type inference (default: 1000)')
parser.add_argument('--batch-size', type=int, default=1000, help='Insert batch size (default: 1000)')
code
args = parser.parse_args()
converter = CSVtoSQLite(args.csv_file, args.db, args.table, args.delimiter, args.sample_size, args.batch_size)
result = converter.convert()
print(f"\nConversion summary: {result['rows']:,} rows inserted into {result['table']}")
if result['errors'] > 0:
print(f"Warning: {result['errors']} rows encountered errors during conversion")
Setting up the argument parser to handle CSV file input along with optional parameters for database name, table name, delimiter, and batch processing sizes. Once arguments are parsed, I instantiate the converter and execute the conversion, then display a final summary with row counts and any errors encountered.
CSV to SQLite with Type Inference
Here's a comprehensive solution that analyzes CSV data and automatically infers column types: