db_create.py 12 KB

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