db_compare.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import codecs
  2. import json
  3. from pathlib import Path
  4. import pandas as pd
  5. import pyodbc
  6. from sqlalchemy import create_engine
  7. from database.db_create import get_import_config
  8. from database.model import DatabaseInspect, DbCreateConfig, create_db_ini, load_config
  9. def decode_ts(ts_binary):
  10. return "0x" + codecs.encode(ts_binary, "hex_codec").decode()
  11. def compare(config_file: str = "database/CARLO.json"):
  12. cfg = load_config(config_file)
  13. create_db_ini(cfg)
  14. base_dir = str(Path(config_file).parent.parent.resolve())
  15. config = get_import_config(f"{base_dir}/config/{cfg.csv_file}", cfg.dest_dsn.database)
  16. source_db = DatabaseInspect(cfg.source_dsn, source=True)
  17. source_tables = source_db.get_tables()
  18. print(json.dumps(source_db.get_prefix(), indent=2))
  19. dest_db = DatabaseInspect(cfg.dest_dsn)
  20. dest_tables = dest_db.get_tables()
  21. for _, current_table in config.iterrows():
  22. dest_row_count = {}
  23. dest_timestamp = {}
  24. if current_table["dest"] in dest_tables:
  25. full_table_name = f'[{current_table["dest_db"]}].[{cfg.dest_dsn.schema}].[{current_table["dest"]}]'
  26. query_count_dest = f"SELECT [Client_DB], COUNT(*) as [Rows] FROM {full_table_name} GROUP BY [Client_DB]"
  27. q = dest_db.cursor.execute(query_count_dest)
  28. dest_row_count = dict([(col[0], col[1]) for col in q.fetchall()])
  29. query_timestamp_dest = (
  30. f"SELECT [Client_DB], max(timestamp) as [TS] FROM {full_table_name} GROUP BY [Client_DB]"
  31. )
  32. q = dest_db.cursor.execute(query_timestamp_dest)
  33. dest_timestamp = dict([(col[0], decode_ts(col[1])) for col in q.fetchall()])
  34. source_row_count = {}
  35. source_row_count_ts = {}
  36. for client_db, prefix in cfg.clients.items():
  37. source_table = current_table["source"].format(prefix)
  38. source_table2 = source_table.split(".")[-1][1:-1]
  39. if source_table in source_tables or source_table2 in source_tables:
  40. if not pd.isnull(current_table["query"]):
  41. select_query = current_table["query"].format(prefix, cfg.filter[0], cfg.filter[1])
  42. elif "." in source_table or cfg.source_dsn.schema == "":
  43. if source_table[0] != "[":
  44. source_table = f"[{source_table}]"
  45. select_query = f"SELECT T1.* FROM {source_table} T1 "
  46. else:
  47. select_query = f"SELECT T1.* FROM [{cfg.source_dsn.schema}].[{source_table}] T1 "
  48. if not pd.isnull(current_table["filter"]):
  49. select_query += " WHERE " + current_table["filter"].format("", cfg.filter[0], cfg.filter[1])
  50. elif "WHERE" not in select_query:
  51. select_query += " WHERE 1 = 1"
  52. query_count_source = select_query.replace("T1.*", "COUNT(*) as [Rows]")
  53. # print(query_count_source)
  54. q = source_db.cursor.execute(query_count_source)
  55. source_row_count[client_db] = q.fetchone()[0]
  56. query_ts = query_count_source
  57. ts = dest_timestamp.get(client_db, "0x0000000000000000")
  58. if "WHERE" in query_ts:
  59. query_ts = query_ts.replace("WHERE", f"WHERE T1.[timestamp] <= convert(binary(8), '{ts}', 1) AND")
  60. else:
  61. query_ts += f" WHERE T1.[timestamp] <= convert(binary(8), '{ts}', 1)"
  62. # print(query_ts)
  63. try:
  64. q = source_db.cursor.execute(query_ts)
  65. source_row_count_ts[client_db] = q.fetchone()[0]
  66. except pyodbc.ProgrammingError:
  67. pass
  68. if dest_row_count.get(client_db, 0) != source_row_count.get(client_db, 0):
  69. print(f"Tabelle {current_table['dest']} mit Client {client_db} stimmt nicht ueberein.")
  70. print(f" Quelle: {source_row_count.get(client_db, 0):>8}")
  71. print(f" Quelle (bis ts): {source_row_count_ts.get(client_db, 0):>8}")
  72. print(f" dest: {dest_row_count.get(client_db, 0):>8}")
  73. compare_details(current_table, client_db, source_db, dest_db, query_count_source, full_table_name, cfg)
  74. def compare_details(
  75. current_table: pd.Series,
  76. client_db: str,
  77. source_db: DatabaseInspect,
  78. dest_db: DatabaseInspect,
  79. query_count_source: str,
  80. full_table_name: str,
  81. cfg: DbCreateConfig,
  82. ):
  83. table_client = f'{current_table["dest"]}_{client_db}'
  84. pkey = dest_db.get_pkey(current_table["dest"], current_table["dest_db"])
  85. cols = pkey + ["timestamp"]
  86. if "Client_DB" in cols:
  87. cols.remove("Client_DB")
  88. if "CLIENT_DB" in cols:
  89. cols.remove("CLIENT_DB")
  90. query_cols = ", ".join([f"T1.[{c}]" for c in cols])
  91. query_source = query_count_source.replace("COUNT(*) as [Rows]", query_cols)
  92. query_source += f" ORDER BY {query_cols}"
  93. query_dest = (
  94. f"SELECT {query_cols} FROM {full_table_name} T1 WHERE T1.[Client_DB] = '{client_db}' ORDER BY {query_cols}"
  95. )
  96. source_file = f"{cfg.stage_dir}\\source\\{table_client}.csv"
  97. source_data = pd.read_sql(query_source, create_engine(source_db.conn_string_sqlalchemy))
  98. source_data["timestamp"] = source_data["timestamp"].apply(decode_ts)
  99. source_data.to_csv(source_file, index=False)
  100. dest_file = f"{cfg.stage_dir}\\dest\\{table_client}.csv"
  101. dest_data = pd.read_sql(query_dest, create_engine(dest_db.conn_string_sqlalchemy))
  102. dest_data["timestamp"] = dest_data["timestamp"].apply(decode_ts)
  103. dest_data.to_csv(dest_file, index=False)
  104. cols_without_ts = cols[:-1]
  105. only_in_source_file = f"{cfg.stage_dir}\\diff\\{table_client}_only_in_source.sql"
  106. only_in_source = pd.merge(source_data, dest_data, how="left", on=cols_without_ts)
  107. only_in_source = only_in_source[pd.isna(only_in_source["timestamp_y"])]
  108. if only_in_source.shape[0] > 0:
  109. ts_list = ", ".join(only_in_source.to_dict(orient="list")["timestamp_x"])
  110. query = query_count_source.replace("COUNT(*) as [Rows]", "T1.*")
  111. query += f" AND T1.[timestamp] IN ({ts_list})"
  112. with open(only_in_source_file, "w") as fwh:
  113. fwh.write(query)
  114. only_in_dest_file = f"{cfg.stage_dir}\\diff\\{table_client}_only_in_dest.sql"
  115. only_in_dest = pd.merge(dest_data, source_data, how="left", on=cols_without_ts)
  116. only_in_dest = only_in_dest[pd.isna(only_in_dest["timestamp_y"])]
  117. if only_in_dest.shape[0] > 0:
  118. ts_list = ", ".join(only_in_dest.to_dict(orient="list")["timestamp_x"])
  119. query = f"SELECT T1.* FROM {full_table_name} T1 WHERE T1.[Client_DB] = '{client_db}' AND T1.[timestamp] IN ({ts_list})"
  120. with open(only_in_dest_file, "w") as fwh:
  121. fwh.write(query)
  122. not_updated_file = f"{cfg.stage_dir}\\diff\\{table_client}_not_updated.sql"
  123. not_updated = pd.merge(source_data, dest_data, how="inner", on=cols_without_ts)
  124. not_updated = not_updated[not_updated["timestamp_x"] != not_updated["timestamp_y"]]
  125. if not_updated.shape[0] > 0:
  126. ts_list = ", ".join(not_updated.to_dict(orient="list")["timestamp_x"])
  127. query = query_count_source.replace("COUNT(*) as [Rows]", "T1.*")
  128. query += f" AND T1.[timestamp] IN ({ts_list})"
  129. with open(not_updated_file, "w") as fwh:
  130. fwh.write(query)