No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

merge_comuni.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Script per il merge dei file comune.sql di IT e CH
  5. Aggiunge le colonne created_at, updated_at, nazione_id
  6. """
  7. import re
  8. import os
  9. def parse_sql_file(file_path):
  10. """Parsa un file SQL e estrae le righe INSERT da tutte le query"""
  11. with open(file_path, 'r', encoding='utf-8') as f:
  12. content = f.read()
  13. # Trova tutte le sezioni VALUES
  14. values_matches = re.findall(r'VALUES\s*(.*?);', content, re.DOTALL | re.IGNORECASE)
  15. if not values_matches:
  16. print(f"Errore: non trovo la sezione VALUES in {file_path}")
  17. return []
  18. # Combina tutte le sezioni VALUES
  19. all_values_section = ',\n'.join(values_matches)
  20. # Estrae le righe individuali
  21. rows = []
  22. # Pattern migliorato per matchare le righe con apostrofi escaped: (id, provincia_id, nome, codice_catastale, ...)
  23. # Gestisce sia apostrofi normali che escaped (\')
  24. pattern = r'\((\d+),\s*(\d+),\s*\'((?:[^\'\\]|\\.)*)\',\s*\'?([^\',]*)\'?'
  25. matches = re.findall(pattern, all_values_section)
  26. for match in matches:
  27. id_val, provincia_id, nome, codice_catastale = match
  28. # Decodifica gli apostrofi escaped
  29. nome = nome.replace("\\'", "'")
  30. rows.append({
  31. 'id': int(id_val),
  32. 'provincia_id': int(provincia_id),
  33. 'nome': nome,
  34. 'codice_catastale': codice_catastale if codice_catastale != 'NULL' else None
  35. })
  36. return rows
  37. def generate_merged_sql(it_rows, ch_rows, output_file):
  38. """Genera il file SQL di merge"""
  39. with open(output_file, 'w', encoding='utf-8') as f:
  40. f.write("INSERT INTO `comune` (\n")
  41. f.write(" `id`,\n")
  42. f.write(" `provincia_id`,\n")
  43. f.write(" `nome`,\n")
  44. f.write(" `codice_catastale`,\n")
  45. f.write(" `created_at`,\n")
  46. f.write(" `updated_at`,\n")
  47. f.write(" `nazione_id`\n")
  48. f.write(") VALUES\n")
  49. all_rows = []
  50. # Processa righe IT (nazione_id = 118, created_at/updated_at = NULL)
  51. for row in it_rows:
  52. nome_escaped = row['nome'].replace("'", "\\'")
  53. codice = f"'{row['codice_catastale']}'" if row['codice_catastale'] else 'NULL'
  54. all_rows.append(
  55. f"({row['id']}, {row['provincia_id']}, '{nome_escaped}', {codice}, NULL, NULL, 118)"
  56. )
  57. # Processa righe CH (nazione_id = 220, created_at/updated_at dal file originale)
  58. # Rinumera gli ID partendo da 110015
  59. new_ch_id = 110015
  60. for row in ch_rows:
  61. nome_escaped = row['nome'].replace("'", "\\'")
  62. codice = f"'{row['codice_catastale']}'" if row['codice_catastale'] else 'NULL'
  63. all_rows.append(
  64. f"({new_ch_id}, {row['provincia_id']}, '{nome_escaped}', {codice}, NULL, NULL, 220)"
  65. )
  66. new_ch_id += 1
  67. # Scrivi tutte le righe
  68. f.write(",\n".join(all_rows))
  69. f.write(";\n")
  70. # Aggiungi statistiche
  71. f.write(f"\n-- Statistiche merge:\n")
  72. f.write(f"-- Comuni IT: {len(it_rows)} (ID originali, nazione_id = 118)\n")
  73. f.write(f"-- Comuni CH: {len(ch_rows)} (ID da {110015} a {110015 + len(ch_rows) - 1}, nazione_id = 220)\n")
  74. f.write(f"-- Totale comuni: {len(all_rows)}\n")
  75. def main():
  76. # Percorsi dei file
  77. base_dir = os.path.dirname(os.path.abspath(__file__))
  78. it_file = os.path.join(base_dir, 'it', 'comune.sql')
  79. ch_file = os.path.join(base_dir, 'ch', 'comune.sql')
  80. output_file = os.path.join(base_dir, 'comune_merged.sql')
  81. print("Inizio parsing file IT...")
  82. it_rows = parse_sql_file(it_file)
  83. print(f"Trovate {len(it_rows)} righe nel file IT")
  84. print("Inizio parsing file CH...")
  85. ch_rows = parse_sql_file(ch_file)
  86. print(f"Trovate {len(ch_rows)} righe nel file CH")
  87. print("Generazione file di merge...")
  88. generate_merged_sql(it_rows, ch_rows, output_file)
  89. print(f"File di merge generato: {output_file}")
  90. print(f"Totale righe nel file finale: {len(it_rows) + len(ch_rows)}")
  91. if __name__ == "__main__":
  92. main()