db_create.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import json
  2. import os
  3. from dataclasses import dataclass, field
  4. from pathlib import Path
  5. import pandas as pd
  6. import pyodbc
  7. @dataclass
  8. class DsnConfig:
  9. user: str = "sa"
  10. password: str = "Mffu3011#"
  11. server: str = "LOCALHOST\\GLOBALCUBE"
  12. database: str = "CARLO"
  13. driver: str = "mssql"
  14. schema: str = "import"
  15. @dataclass
  16. class DbCreateConfig:
  17. name: str = "CARLO"
  18. csv_file: str = "CARLO.csv"
  19. clients: dict[str, str] = field(default_factory=lambda: {"1": "M und S Fahrzeughandel GmbH"})
  20. filter: list[str] = (["2018-01-01T00:00:00", "2022-01-01T00:00:00"],)
  21. source_dsn: DsnConfig = None
  22. target_dsn: DsnConfig = None
  23. stage_dir: str = "..\\temp"
  24. batch_dir: str = "..\\batch"
  25. logs_dir: str = "..\\logs"
  26. class database_inspect:
  27. tables = []
  28. def __init__(self, dsn: DsnConfig, source=False):
  29. self.dsn = dsn
  30. self.type = "SOURCE" if source else "DEST"
  31. self.cursor = self.connect()
  32. @property
  33. def conn_string(self):
  34. if self.dsn.driver == "mssql":
  35. return ";".join(
  36. [
  37. "Driver={SQL Server Native Client 11.0}",
  38. f"Server={self.dsn.server}",
  39. f"Database={self.dsn.database}",
  40. f"Uid={self.dsn.user}",
  41. f"Pwd={self.dsn.password}",
  42. ]
  43. )
  44. if self.dsn.driver == "mysql":
  45. return f"mysql+pymysql://{self.dsn.user}:{self.dsn.password}@{self.dsn.server}/{self.dsn.database}?charset=utf8mb4"
  46. return ";".join(
  47. [
  48. "Driver={PostgreSQL Unicode}",
  49. f"Server={self.dsn.server}",
  50. "Port=5432",
  51. f"Database={self.dsn.database}",
  52. f"Uid={self.dsn.user}",
  53. f"Pwd={self.dsn.password}",
  54. ]
  55. )
  56. # f"DSN={self.dsn.server};UID={self.dsn.user};PWD={self.dsn.password}"
  57. @property
  58. def conn_ini(self):
  59. return "\r\n".join(
  60. [
  61. f'{self.type}_SERVER="{self.dsn.server}"',
  62. f'{self.type}_USER="{self.dsn.user}"',
  63. f'{self.type}_PASSWORD="{self.dsn.password}"',
  64. f'{self.type}_DATABASE="{self.dsn.database}"',
  65. ]
  66. )
  67. @property
  68. def bcp_conn_params(self):
  69. return f"-S {self.dsn.server} -d {self.dsn.database} -U {self.dsn.user} -P {self.dsn.password}"
  70. def connect(self):
  71. c = pyodbc.connect(self.conn_string)
  72. return c.cursor()
  73. def get_tables(self):
  74. tables = [x[2] for x in self.cursor.tables(tableType="TABLE")]
  75. views = [x[2] for x in self.cursor.tables(tableType="VIEW")]
  76. self.tables = tables + views
  77. return self.tables
  78. def get_prefix(self):
  79. if (len(self.tables)) == 0:
  80. self.get_tables()
  81. source_tables_prefix = dict(enumerate(sorted(list(set([t.split("$")[0] for t in self.tables if "$" in t]))), 1))
  82. if len(source_tables_prefix) == 0:
  83. q = self.cursor.execute("select name FROM sys.databases")
  84. source_tables_prefix = [x[0] for x in q.fetchall()]
  85. return source_tables_prefix
  86. def get_columns(self, table):
  87. source_insp_cols = [col.column_name for col in self.cursor.columns(table=table)]
  88. if len(source_insp_cols) == 0:
  89. q = self.cursor.execute(
  90. "SELECT COLUMN_NAME as column_name FROM information_schema.columns "
  91. + f"WHERE TABLE_NAME = '{self.convert_table(table)}'"
  92. )
  93. source_insp_cols = [col[0] for col in q.fetchall()]
  94. return source_insp_cols
  95. def get_columns_is_typeof_str(self, table):
  96. source_insp_cols = [
  97. col.data_type in [pyodbc.SQL_CHAR, pyodbc.SQL_VARCHAR] for col in self.cursor.columns(table=table)
  98. ]
  99. if len(source_insp_cols) == 0:
  100. q = self.cursor.execute(
  101. "SELECT COLLATION_NAME as column_collation FROM information_schema.columns "
  102. + f"WHERE TABLE_NAME = '{self.convert_table(table)}'"
  103. )
  104. source_insp_cols = [len(col[0]) > 0 for col in q.fetchall()]
  105. return source_insp_cols
  106. def get_pkey(self, table):
  107. source_insp_cols = [col.column_name for col in self.cursor.primaryKeys(table=table)]
  108. if len(source_insp_cols) == 0:
  109. q = self.cursor.execute(
  110. "SELECT COLUMN_NAME "
  111. "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE "
  112. "WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 "
  113. f"AND TABLE_NAME = '{self.convert_table(table)}' " # AND TABLE_SCHEMA = 'dbo'"
  114. )
  115. source_insp_cols = [col[0] for col in q.fetchall()]
  116. return source_insp_cols
  117. def convert_table(self, table):
  118. if "." in table:
  119. table = table.split(".")[-1]
  120. if "[" in table:
  121. table = table[1:-1]
  122. return table
  123. def load_config(config_file: str):
  124. cfg_import = json.load(open(config_file, "r", encoding="latin-1"))
  125. base_dir = Path(config_file).resolve().parent
  126. cfg_import["name"] = Path(config_file).stem
  127. if "logs_dir" not in cfg_import:
  128. cfg_import["logs_dir"] = "..\\logs"
  129. for folder in ["stage_dir", "batch_dir", "logs_dir"]:
  130. if cfg_import[folder].startswith(".."):
  131. cfg_import[folder] = str(base_dir.joinpath(cfg_import[folder]).resolve())
  132. os.makedirs(cfg_import[folder], exist_ok=True)
  133. cfg_import["source_dsn"] = DsnConfig(**cfg_import["source_dsn"])
  134. cfg_import["target_dsn"] = DsnConfig(**cfg_import["target_dsn"])
  135. return DbCreateConfig(**cfg_import)
  136. def get_import_config(filename: str, db_name: str):
  137. df = pd.read_csv(filename, sep=";", encoding="latin-1")
  138. if "cols" not in df.columns:
  139. df["target_db"] = db_name
  140. df["cols"] = ""
  141. df[["source", "target", "target_db", "filter", "query", "iterative", "cols"]].to_csv(
  142. filename, sep=";", encoding="latin-1", index=False
  143. )
  144. return df[df["target"].notnull()]
  145. def create(config_file: str = "database/CARLO.json"):
  146. cfg = load_config(config_file)
  147. base_dir = str(Path(cfg.batch_dir).parent)
  148. config = get_import_config(f"{base_dir}/config/{cfg.csv_file}", cfg.target_dsn.database)
  149. source_db = database_inspect(cfg.source_dsn, source=True)
  150. source_tables = source_db.get_tables()
  151. print(json.dumps(source_db.get_prefix(), indent=2))
  152. target_db = database_inspect(cfg.target_dsn)
  153. target_tables = target_db.get_tables()
  154. for _, current_table in config.iterrows():
  155. with open(f"{cfg.batch_dir}/{current_table['target']}.bat", "w", encoding="cp850") as f:
  156. f.write("@echo off \n")
  157. f.write("rem ==" + current_table["target"] + "==\n")
  158. if not current_table["target"] in target_tables:
  159. f.write(f"echo Ziel-Tabelle '{current_table['target']}' existiert nicht!\n")
  160. print(f"Ziel-Tabelle '{current_table['target']}' existiert nicht!")
  161. continue
  162. f.write(f"del {cfg.stage_dir}\\{current_table['target']}*.* /Q /F >nul 2>nul \n")
  163. f.write(
  164. f"sqlcmd.exe {target_db.bcp_conn_params} -p "
  165. + f"-Q \"TRUNCATE TABLE [{cfg.target_dsn.schema}].[{current_table['target']}]\" \n"
  166. )
  167. target_columns_list = target_db.get_columns(current_table["target"])
  168. target_column_types = target_db.get_columns_is_typeof_str(current_table["target"])
  169. if "CLIENT_DB" in target_columns_list:
  170. target_columns_list.remove("CLIENT_DB")
  171. target_columns_list.append("Client_DB")
  172. target_columns = set(target_columns_list)
  173. for client_db, prefix in cfg.clients.items():
  174. source_table = current_table["source"].format(prefix)
  175. if source_table not in source_tables:
  176. source_table2 = source_db.convert_table(source_table)
  177. if source_table2 not in source_tables:
  178. f.write(f"echo Quell-Tabelle '{source_table}' existiert nicht!\n")
  179. print(f"Quell-Tabelle '{source_table}' existiert nicht!")
  180. continue
  181. source_columns = set(source_db.get_columns(source_table))
  182. intersect = source_columns.intersection(target_columns)
  183. # print("Auf beiden Seiten: " + ";".join(intersect))
  184. diff1 = source_columns.difference(target_columns)
  185. if len(diff1) > 0:
  186. f.write("rem Nur in Quelle: " + ";".join(diff1) + "\n")
  187. diff2 = target_columns.difference(source_columns)
  188. if "Client_DB" not in diff2:
  189. f.write("echo Spalte 'Client_DB' fehlt!\n")
  190. print(f"Ziel-Tabelle '{current_table['target']}' Spalte 'Client_DB' fehlt!")
  191. continue
  192. diff2.remove("Client_DB")
  193. if len(diff2) > 0:
  194. f.write("rem Nur in Ziel: " + ";".join(diff2) + "\n")
  195. if not pd.isnull(current_table["query"]):
  196. select_query = current_table["query"].format(prefix, cfg.filter[0], cfg.filter[1])
  197. elif "." in source_table or cfg.source_dsn.schema == "":
  198. if source_table[0] != "[":
  199. source_table = f"[{source_table}]"
  200. select_query = f"SELECT T1.* FROM {source_table} T1 "
  201. else:
  202. select_query = f"SELECT T1.* FROM [{cfg.source_dsn.schema}].[{source_table}] T1 "
  203. if not pd.isnull(current_table["filter"]):
  204. select_query += " WHERE " + current_table["filter"].format("", cfg.filter[0], cfg.filter[1])
  205. # select_columns = "T1.[" + "], T1.[".join(intersect) + "],"
  206. select_columns = ""
  207. for col, is_char_type in zip(target_columns_list, target_column_types):
  208. if col in intersect:
  209. if is_char_type:
  210. select_columns += f"dbo.cln(T1.[{col}]), "
  211. else:
  212. select_columns += f"T1.[{col}], "
  213. elif col == "Client_DB":
  214. select_columns += f"'{client_db}' as \\\"Client_DB\\\", "
  215. else:
  216. select_columns += "'' as \\\"" + col + '\\", '
  217. select_query = select_query.replace("T1.*", select_columns[:-2])
  218. if "timestamp" in source_columns:
  219. select_query += " ORDER BY T1.[timestamp] "
  220. else:
  221. print(current_table["target"] + " hat kein timestamp-Feld")
  222. pkey = target_db.get_pkey(current_table["target"])
  223. if len(pkey) == 0:
  224. print(current_table["target"] + " hat keinen Primaerschluessel")
  225. select_query = select_query.replace("%", "%%") # batch-Problem
  226. stage_csv = f"{cfg.stage_dir}\\{current_table['target']}_{client_db}.csv"
  227. logfile = f"{cfg.logs_dir}\\{current_table['target']}_{client_db}"
  228. # insert_query = f"LOAD DATA INFILE '{stage_csv}' INTO TABLE {current_table['target']} FIELDS TERMINATED BY ','
  229. # ENCLOSED BY '\"' LINES TERMINATED BY '\n';"
  230. # print(select_query)
  231. bulk_copy = "bcp" if cfg.source_dsn.driver == "mssql" else "cet"
  232. f.write(
  233. f'{bulk_copy} "{select_query}" queryout "{stage_csv}" {source_db.bcp_conn_params} -c -C 65001 -m 1000 '
  234. + f'-e "{logfile}.queryout.log" > "{logfile}.bcp1.log" \n'
  235. )
  236. f.write(f'type "{logfile}.bcp1.log" | findstr -v "1000" \n')
  237. f.write(
  238. f"bcp [{cfg.target_dsn.schema}].[{current_table['target']}] in \"{stage_csv}\" {target_db.bcp_conn_params} "
  239. + f'-c -C 65001 -m 1000 -e "{logfile}.in.log" > "{logfile}.bcp2.log" \n'
  240. )
  241. f.write(f'type "{logfile}.bcp2.log" | findstr -v "1000" \n')
  242. f.write(f'del "{stage_csv}" /F >nul 2>nul \n')
  243. with open(f"{cfg.batch_dir}/_{cfg.name}.bat", "w", encoding="cp850") as f:
  244. f.write("@echo off & cd /d %~dp0 \n")
  245. f.write(f"del {cfg.stage_dir}\\*.* /Q /F >nul 2>nul \n\n")
  246. for index, current_table in config.iterrows():
  247. f.write(f"echo =={current_table['target']}==\n")
  248. f.write(f"echo {current_table['target']} >CON \n")
  249. f.write(f"call {current_table['target']}.bat\n\n")
  250. if __name__ == "__main__":
  251. create()