db_create.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import json
  2. import sys
  3. import pandas as pd
  4. sys.path.insert(0, "C:\\Projekte\\tools")
  5. from database.model import DbCreateConfig, DestTable, SourceTable2 # noqa:E402
  6. def get_import_config(filename: str, db_name: str) -> pd.DataFrame:
  7. df = pd.read_csv(filename, sep=";", encoding="latin-1")
  8. if "dest" not in df.columns:
  9. df["dest"] = df["target"]
  10. df["dest_db"] = db_name
  11. df["cols"] = ""
  12. df[["source", "dest", "dest_db", "filter", "query", "iterative", "cols"]].to_csv(
  13. filename, sep=";", encoding="latin-1", index=False
  14. )
  15. return df[df["dest"].notnull()]
  16. def get_table_config(cfg: DbCreateConfig) -> list[DestTable]:
  17. config = get_import_config(cfg.csv_file, cfg.dest_dsn.database)
  18. SourceTable2.source_inspect = cfg.source_inspect
  19. SourceTable2.cfg = cfg
  20. table_config = [DestTable(*row.values()) for row in config.to_dict(orient="records")]
  21. for dest_table in table_config:
  22. dest_table.cfg = cfg
  23. dest_table.dest_inspect = cfg.dest_inspect
  24. dest_table.source_tables = []
  25. for client_db, prefix in cfg.clients.items():
  26. st = SourceTable2(dest_table.source, client_db, prefix)
  27. st.dest_table = dest_table
  28. dest_table.source_tables.append(st)
  29. return table_config
  30. def create(config_file: str = "database/CARLO.json"):
  31. cfg = DbCreateConfig.load_config(config_file)
  32. cfg.create_db_ini()
  33. print(json.dumps(cfg.source_inspect.get_prefix(), indent=2))
  34. table_config = get_table_config(cfg)
  35. for dest_table in table_config:
  36. with open(dest_table.table_batch_file, "w", encoding="cp850") as f:
  37. f.write("@echo off\n")
  38. f.write(f'call "{cfg.scripts_dir}\\config2.bat"\n')
  39. f.write("rem ==" + dest_table.dest + "==\n")
  40. if dest_table.dest not in cfg.dest_inspect.tables_list:
  41. f.write(f"echo Ziel-Tabelle '{dest_table.dest}' existiert nicht!\n")
  42. print(f"Ziel-Tabelle '{dest_table.dest}' existiert nicht!")
  43. continue
  44. f.write(f"del {cfg.logs_dir}\\{dest_table.dest}*.* /Q /F >nul 2>nul\n\n")
  45. f.write('if not "%1"=="" goto :increment\n')
  46. f.write("\n:full\n")
  47. f.write(f' call sql_query.bat "TRUNCATE TABLE {dest_table.full_table_name}"\n')
  48. for source_table in dest_table.source_tables:
  49. if source_table.table_name not in cfg.source_inspect.tables_list:
  50. source_table2 = cfg.source_inspect.convert_table(source_table.table_name)
  51. if source_table2 not in cfg.source_inspect.tables_list:
  52. f.write(f"echo Quell-Tabelle '{source_table.table_name}' existiert nicht!\n")
  53. print(f"Quell-Tabelle '{source_table.table_name}' existiert nicht!")
  54. continue
  55. select_query = source_table.select_query_with_columns.replace("%", "%%%%") # batch-Problem
  56. f.write(source_table.info)
  57. if select_query == "":
  58. print(f"Ziel-Tabelle '{dest_table.dest}' Spalte 'Client_DB' fehlt!")
  59. continue
  60. f.write(f' call bcp_queryout.bat "{source_table.table_client}" "{select_query}"\n')
  61. f.write(
  62. f' call bcp_in.bat "{source_table.table_client}" '
  63. f'"[{cfg.dest_dsn.schema}].[{dest_table.dest}]" "{dest_table.dest_db}"\n'
  64. )
  65. f.write(" goto :cleanup\n\n")
  66. f.write(":increment\n")
  67. f.write(f' call sql_query.bat "TRUNCATE TABLE {dest_table.temp_table_name}"\n\n')
  68. for source_table in dest_table.source_tables:
  69. select_query = source_table.select_query_with_columns
  70. convert_timestamp = "T1.[timestamp] > convert(binary(8), '%TS%', 1)"
  71. if "WHERE" in select_query:
  72. select_query = select_query.replace("WHERE", f"WHERE {convert_timestamp} AND")
  73. else:
  74. print("Dont know where to put WHERE")
  75. f.write(
  76. f' call sql_timestamp.bat "{source_table.table_client}" "{dest_table.full_table_name}" "{source_table.client_db}"\n'
  77. )
  78. f.write(f' call bcp_queryout.bat "{source_table.table_client}" "{select_query}"\n')
  79. f.write(
  80. f' call bcp_in.bat "{source_table.table_client}" "[temp].[{dest_table.dest}]" "{cfg.temp_db}"\n\n'
  81. )
  82. if dest_table.delete_query == "":
  83. print(dest_table.dest + " hat keinen Primaerschluessel")
  84. f.write(f" rem {dest_table.dest} hat keinen Primaerschluessel")
  85. else:
  86. f.write(f' call sql_query.bat "{dest_table.delete_query}"\n')
  87. f.write(f' call sql_query.bat "{dest_table.insert_query}"\n')
  88. f.write("\n:cleanup\n")
  89. for source_table in dest_table.source_tables:
  90. f.write(f' call delete.bat "{source_table.stage_csv}"\n')
  91. with open(f"{cfg.batch_dir}/_{cfg.name}.bat", "w", encoding="cp850") as f:
  92. f.write("@echo off & cd /d %~dp0\n")
  93. f.write(f"del {cfg.stage_dir}\\*.* /Q /F >nul 2>nul\n\n")
  94. for dest_table in table_config:
  95. f.write(f"echo =={dest_table.dest}==\n")
  96. f.write(f"echo {dest_table.dest} >CON\n")
  97. f.write(f"call {cfg.batch_dir}\\{dest_table.dest}.bat 1\n\n")
  98. with open(f"{cfg.batch_dir}/_{cfg.name}_full_load.bat", "w", encoding="cp850") as f:
  99. f.write("@echo off & cd /d %~dp0\n")
  100. f.write(f"del {cfg.stage_dir}\\*.* /Q /F >nul 2>nul\n\n")
  101. for dest_table in table_config:
  102. f.write(f"echo =={dest_table.dest}==\n")
  103. f.write(f"echo {dest_table.dest} >CON\n")
  104. f.write(f"call {cfg.batch_dir}\\{dest_table.dest}.bat\n\n")
  105. if __name__ == "__main__":
  106. create()