db_create.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import json
  2. from collections import namedtuple
  3. from pathlib import Path
  4. import pandas as pd
  5. import plac
  6. import pyodbc
  7. DbCreateConfig = namedtuple('DbCreateConfig', 'name csv_file clients filter source_dsn target_dsn stage_dir batch_dir')
  8. DsnConfig = namedtuple('DsnConfig', 'user password server database driver schema')
  9. cfg = DbCreateConfig(**{
  10. 'name': 'CARLO',
  11. 'csv_file': 'CARLO.csv',
  12. 'clients': {'1': 'M und S Fahrzeughandel GmbH'},
  13. 'filter': ['01.01.2018', '01.01.2019'],
  14. 'source_dsn': {'user': 'sa', 'password': 'Mffu3011#', 'server': 'GC-SERVER1\\GLOBALCUBE', 'database': 'DE0017', 'driver': 'mssql', 'schema': 'dbo'},
  15. 'target_dsn': {'user': 'sa', 'password': 'Mffu3011#', 'server': 'GC-SERVER1\\GLOBALCUBE', 'database': 'CARLO2', 'driver': 'mssql', 'schema': 'import'},
  16. 'stage_dir': '..\\temp',
  17. 'batch_dir': '..\\batch'
  18. })
  19. class database_inspect():
  20. tables = []
  21. def __init__(self, dsn):
  22. self.dsn = DsnConfig(**dsn)
  23. self.cursor = self.connect()
  24. def conn_string(self):
  25. if self.dsn.driver == 'mssql':
  26. return 'Driver={SQL Server Native Client 11.0};' + f"Server={self.dsn.server};Database={self.dsn.database};Uid={self.dsn.user};Pwd={self.dsn.password}"
  27. if self.dsn.driver == 'mysql':
  28. return f"mysql+pymysql://{self.dsn.user}:{self.dsn.password}@{self.dsn.server}/{self.dsn.database}?charset=utf8mb4"
  29. return f"DSN={self.dsn.server};UID={self.dsn.user};PWD={self.dsn.password}"
  30. def bcp_conn_params(self):
  31. return f"-S {self.dsn.server} -d {self.dsn.database} -U {self.dsn.user} -P {self.dsn.password}"
  32. def connect(self):
  33. c = pyodbc.connect(self.conn_string())
  34. return c.cursor()
  35. def get_tables(self):
  36. tables = [x[2] for x in self.cursor.tables(tableType='TABLE')]
  37. views = [x[2] for x in self.cursor.tables(tableType='VIEW')]
  38. self.tables = tables + views
  39. return self.tables
  40. def get_prefix(self):
  41. if (len(self.tables)) == 0:
  42. self.get_tables()
  43. source_tables_prefix = dict(enumerate(sorted(list(set([t.split('$')[0] for t in self.tables if '$' in t]))), 1))
  44. if len(source_tables_prefix) == 0:
  45. q = self.cursor.execute('select name FROM sys.databases')
  46. source_tables_prefix = [x[0] for x in q.fetchall()]
  47. return source_tables_prefix
  48. def get_columns(self, table):
  49. source_insp_cols = [col.column_name for col in self.cursor.columns(table=table)]
  50. if len(source_insp_cols) == 0:
  51. q = self.cursor.execute(f"SELECT COLUMN_NAME as column_name FROM information_schema.columns WHERE TABLE_NAME = '{self.convert_table(table)}'")
  52. source_insp_cols = [col[0] for col in q.fetchall()]
  53. return source_insp_cols
  54. def convert_table(self, table):
  55. if '.' in table:
  56. table = table.split('.')[-1]
  57. if '[' in table:
  58. table = table[1:-1]
  59. return table
  60. @plac.pos('config_file', '', type=str)
  61. def create(config_file='dbtools/OPTIMA.json'):
  62. cfg_import = json.load(open(config_file, 'r', encoding='ansi'))
  63. base_dir = Path(config_file).resolve().parent
  64. cfg_import['name'] = Path(config_file).stem
  65. if cfg_import['stage_dir'][:2] == '..':
  66. cfg_import['stage_dir'] = str(base_dir.joinpath(cfg_import['stage_dir']).resolve())
  67. if cfg_import['batch_dir'][:2] == '..':
  68. cfg_import['batch_dir'] = str(base_dir.joinpath(cfg_import['batch_dir']).resolve())
  69. cfg = DbCreateConfig(**cfg_import)
  70. df = pd.read_csv(f"{base_dir}/{cfg.csv_file}", sep=';', encoding='ansi')
  71. config = df[df['target'].notnull()]
  72. print(config.head())
  73. source_db = database_inspect(cfg.source_dsn)
  74. source_tables = source_db.get_tables()
  75. print(source_db.get_prefix())
  76. target_db = database_inspect(cfg.target_dsn)
  77. target_tables = target_db.get_tables()
  78. for index, current_table in config.iterrows():
  79. with open(f"{cfg.batch_dir}/{current_table['target']}.bat", 'w', encoding='cp850') as f:
  80. f.write('@echo off \n')
  81. f.write('rem ==' + current_table['target'] + '==\n')
  82. if not current_table['target'] in target_tables:
  83. f.write(f"echo Ziel-Tabelle '{current_table['target']}' existiert nicht!\n")
  84. print(f"Ziel-Tabelle '{current_table['target']}' existiert nicht!")
  85. continue
  86. f.write(f"del {cfg.stage_dir}\\{current_table['target']}*.* /Q /F >nul 2>nul \n")
  87. f.write(f"sqlcmd.exe {target_db.bcp_conn_params()} -p -Q \"TRUNCATE TABLE [{cfg.target_dsn['schema']}].[{current_table['target']}]\" \n")
  88. target_columns_list = target_db.get_columns(current_table['target'])
  89. if 'CLIENT_DB' in target_columns_list:
  90. target_columns_list.remove('CLIENT_DB')
  91. target_columns_list.append('Client_DB')
  92. target_columns = set(target_columns_list)
  93. for client_db, prefix in cfg.clients.items():
  94. source_table = current_table['source'].format(prefix)
  95. if source_table not in source_tables:
  96. source_table2 = source_db.convert_table(source_table)
  97. if source_table2 not in source_tables:
  98. f.write(f"echo Quell-Tabelle '{source_table}' existiert nicht!\n")
  99. print(f"Quell-Tabelle '{source_table}' existiert nicht!")
  100. continue
  101. source_columns = set(source_db.get_columns(source_table))
  102. intersect = source_columns.intersection(target_columns)
  103. # print("Auf beiden Seiten: " + ";".join(intersect))
  104. diff1 = source_columns.difference(target_columns)
  105. if len(diff1) > 0:
  106. f.write("rem Nur in Quelle: " + ";".join(diff1) + "\n")
  107. diff2 = target_columns.difference(source_columns)
  108. if 'Client_DB' not in diff2:
  109. f.write("echo Spalte 'Client_DB' fehlt!\n")
  110. print(f"Ziel-Tabelle '{current_table['target']}' Spalte 'Client_DB' fehlt!")
  111. continue
  112. diff2.remove('Client_DB')
  113. if len(diff2) > 0:
  114. f.write("rem Nur in Ziel: " + ";".join(diff2) + "\n")
  115. if not pd.isnull(current_table['query']):
  116. select_query = current_table['query'].format(prefix, cfg.filter[0], cfg.filter[1])
  117. elif '.' in source_table or cfg.source_dsn['schema'] == '':
  118. select_query = f"SELECT T1.* FROM \\\"{source_table}\\\" T1 "
  119. else:
  120. select_query = f"SELECT T1.* FROM [{cfg.source_dsn['schema']}].[{source_table}] T1 "
  121. if not pd.isnull(current_table['filter']):
  122. select_query += " WHERE " + current_table['filter'].format("", cfg.filter[0], cfg.filter[1])
  123. # select_columns = "T1.[" + "], T1.[".join(intersect) + "],"
  124. select_columns = ''
  125. for col in target_columns_list:
  126. if col in intersect:
  127. select_columns += f"T1.\\\"{col}\\\", "
  128. elif col == 'Client_DB':
  129. select_columns += "'" + client_db + "' as \\\"Client_DB\\\", "
  130. else:
  131. select_columns += "'' as \\\"" + col + "\\\", "
  132. select_query = select_query.replace("T1.*", select_columns[:-2])
  133. select_query = select_query.replace("%", "%%") # batch-Problem
  134. stage_csv = f"{cfg.stage_dir}\\{current_table['target']}_{client_db}.csv"
  135. # insert_query = f"LOAD DATA INFILE '{stage_csv}' INTO TABLE {current_table['target']} FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';"
  136. # print(select_query)
  137. bulk_copy = 'bcp' if cfg.source_dsn['driver'] == 'mssql' else 'cet'
  138. f.write(f"{bulk_copy} \"{select_query}\" queryout \"{stage_csv}\" {source_db.bcp_conn_params()} -c -C 65001 -e \"{stage_csv[:-4]}.queryout.log\" > \"{stage_csv[:-4]}.bcp1.log\" \n")
  139. f.write(f"type \"{stage_csv[:-4]}.bcp1.log\" | findstr -v \"1000\" \n")
  140. f.write(f"bcp [{cfg.target_dsn['schema']}].[{current_table['target']}] in \"{stage_csv}\" {target_db.bcp_conn_params()} -c -C 65001 -e \"{stage_csv[:-4]}.in.log\" > \"{stage_csv[:-4]}.bcp2.log\" \n")
  141. f.write(f"type \"{stage_csv[:-4]}.bcp2.log\" | findstr -v \"1000\" \n")
  142. with open(f"{cfg.batch_dir}/_{cfg.name}.bat", 'w', encoding='cp850') as f:
  143. f.write("@echo off & cd /d %~dp0 \n")
  144. f.write(f"del {cfg.stage_dir}\\*.* /Q /F >nul 2>nul \n\n")
  145. for index, current_table in config.iterrows():
  146. f.write(f"echo =={current_table['target']}==\n")
  147. f.write(f"echo {current_table['target']} >CON \n")
  148. f.write(f"call {current_table['target']}.bat\n\n")
  149. if __name__ == '__main__':
  150. plac.call(create)