62 lines
2.4 KiB
Python
62 lines
2.4 KiB
Python
import os
|
|
import csv
|
|
|
|
# Directory radice dei CSV (adatta se serve)
|
|
BASE_PATH = "estratti"
|
|
OUT_SQL = "tabelle_generate.sql"
|
|
|
|
# Funzione per indovinare il tipo SQL
|
|
def guess_sql_type(colname):
|
|
col = colname.lower()
|
|
if "id" in col or "cod" in col:
|
|
return "VARCHAR(32)"
|
|
if "data" in col or "dt_" in col or col.startswith("dt"):
|
|
return "DATE"
|
|
if "importo" in col or "saldo" in col or "euro" in col or "consistenza" in col or "credito" in col:
|
|
return "DECIMAL(12,2)"
|
|
if "note" in col or "descr" in col or "oggetto" in col:
|
|
return "TEXT"
|
|
if "anno" in col or "mese" in col or "num" in col or col.startswith("n_") or "progressivo" in col:
|
|
return "INT"
|
|
if "email" in col:
|
|
return "VARCHAR(255)"
|
|
return "VARCHAR(128)"
|
|
|
|
def table_name_from_path(path):
|
|
# es: estratti/0021/generale_stabile/Elenco_destinatari_PEC.csv -> t_0021__generale_stabile__Elenco_destinatari_PEC
|
|
rel_path = os.path.relpath(path, BASE_PATH)
|
|
rel_path = rel_path.replace(os.sep, "__").replace(".csv", "")
|
|
if rel_path[0].isdigit():
|
|
rel_path = "t_" + rel_path
|
|
else:
|
|
rel_path = "t_global__" + rel_path
|
|
return rel_path
|
|
|
|
# Scansione ricorsiva e generazione
|
|
sql_statements = []
|
|
for root, dirs, files in os.walk(BASE_PATH):
|
|
for file in files:
|
|
if file.lower().endswith(".csv"):
|
|
full_path = os.path.join(root, file)
|
|
with open(full_path, newline='', encoding="utf-8") as f:
|
|
reader = csv.reader(f)
|
|
header = next(reader)
|
|
tname = table_name_from_path(full_path)
|
|
sql = [f"-- {full_path} -> {tname}"]
|
|
sql.append(f"CREATE TABLE IF NOT EXISTS `{tname}` (")
|
|
sql.append(" id INT AUTO_INCREMENT PRIMARY KEY,")
|
|
sql.append(" id_amministratore VARCHAR(32),")
|
|
sql.append(" id_condominio VARCHAR(32),")
|
|
for h in header:
|
|
colname = h.strip().replace(" ", "_").replace("-", "_")
|
|
sqltype = guess_sql_type(colname)
|
|
sql.append(f" `{colname}` {sqltype},")
|
|
sql.append(" import_hash VARCHAR(64)")
|
|
sql.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n")
|
|
sql_statements.append("\n".join(sql))
|
|
|
|
# Salva tutto su file
|
|
with open(OUT_SQL, "w", encoding="utf-8") as out:
|
|
out.write("\n".join(sql_statements))
|
|
|
|
print(f"File SQL generato: {OUT_SQL}") |