SQLHandler.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Sep 18 16:20:50 2018
  5. @author: tanya
  6. """
  7. import os
  8. import sys
  9. import re
  10. import sqlalchemy
  11. import sqlparse
  12. import pandas as pd
  13. import warnings
  14. sys.path.append(os.getcwd())
  15. from cdplib.log import Log
  16. from cdplib.Singleton_Threadsafe import SingletonThreadsafe
  17. class SQLHandlerPool(metaclass=SingletonThreadsafe):
  18. '''
  19. '''
  20. def __init__(self, size: int = 20):
  21. self._size = size
  22. self._log = Log(name='SQLHandlerPool')
  23. self._sql_handlers = [SQLHandler() for _ in range(size)]
  24. def aquire(self):
  25. while not self._sql_handlers:
  26. self._sql_handlers = [SQLHandler() for _ in range(self._size)]
  27. self._log.warning("Ran out of SQL handlers, 10 more have been added. Are you sure you've returned yours?")
  28. return self._sql_handlers.pop()
  29. def release(self, sql_handler):
  30. sql_handler._engine.dispose()
  31. if len(self._sql_handlers) < self._size:
  32. self._sql_handlers.append(sql_handler)
  33. class SQLHandler:
  34. '''
  35. Resembles methods for executing sql queries
  36. with different dabase connectors.
  37. Remark:in each method we force new opening and
  38. closing of a database connection,
  39. this avoids errors when parallelizing with multiprocessing.
  40. '''
  41. pass
  42. def __init__(self, db_uri: str = None,
  43. is_case_insensitive: bool = False):
  44. '''
  45. :param str db_uri:
  46. of form
  47. <sqlalchemy_dialect//user:password@host:port/dbname?charset=utf8&local_infile=1>
  48. sqlalchemy dialects:
  49. for mysql : mysql+pymysql
  50. for db2: ibm_db_sa
  51. '''
  52. from sqlalchemy_utils import database_exists, create_database
  53. self._log = Log(name='SQLHandler')
  54. if db_uri is None:
  55. from libraries.configuration import default as cfg
  56. db_uri = "mysql+pymysql://{0}:{1}@{2}:{3}/{4}?charset=utf8&local_infile=1"\
  57. .format(cfg["SQL"]["SQL_USER"],
  58. cfg["SQL"]["SQL_PASSWORD"],
  59. cfg["SQL"]["SQL_HOST"],
  60. cfg["SQL"]["SQL_PORT"],
  61. cfg["SQL"]["SQL_DATABASE_NAME"])
  62. assert(isinstance(db_uri, str)),\
  63. "Parameter 'db_uri' must be of type str"
  64. assert(re.match(r'.+://.+:(.+)?@.+:.+/.+', db_uri) is not None),\
  65. ('database url does not match the pattern: '
  66. 'sqlalchemy_dialect//user:password@host:port/dbname')
  67. self._db_uri = db_uri
  68. engine = sqlalchemy.create_engine(self._db_uri)
  69. if not database_exists(engine.url):
  70. create_database(engine.url)
  71. query = "CREATE DATABASE IF NOT EXISTS {}"\
  72. .format(self._connection_params["db"])
  73. with warnings.catch_warnings():
  74. warnings.simplefilter("ignore")
  75. engine.execute(query)
  76. assert(isinstance(is_case_insensitive, bool)),\
  77. "Parameter 'is_case_sensetive' must of type bool"
  78. if 'ibm' in db_uri and not is_case_insensitive:
  79. raise Exception('Ibm db2 is case insensitive')
  80. self._is_case_insensitive = is_case_insensitive
  81. self._engine = engine
  82. def __del__(self):
  83. self.dispose_engine()
  84. @property
  85. def _connection_params(self) -> dict:
  86. '''
  87. return: connection parameters like user,
  88. password, host, port, and database name
  89. rtype: dict
  90. '''
  91. try:
  92. connection_params = {}
  93. connection_params['user'], connection_params['password'] =\
  94. self._db_uri.split('//')[1]\
  95. .split('@')[0]\
  96. .split(':')
  97. connection_params['host'], connection_params['port'] =\
  98. self._db_uri.split('//')[1]\
  99. .split('@')[1]\
  100. .split('/')[0]\
  101. .split(':')
  102. connection_params['db'] = self._db_uri.split('/')[-1]\
  103. .split('?')[0]
  104. return connection_params
  105. except Exception as e:
  106. err = ("Could not parse connection parameters."
  107. "Finished with error {}")\
  108. .format(e)
  109. self._log.error(err)
  110. raise Exception(err)
  111. def drop_database(self):
  112. '''
  113. '''
  114. database = self._connection_params["db"]
  115. self.execute("DROP DATABASE IF EXISTS {}".format(database))
  116. self._engine.execute("CREATE DATABASE {}".format(database))
  117. self._engine.execute("USE {}".format(database))
  118. @property
  119. def _db_metadata(self) -> dict:
  120. '''
  121. Returns a sql-dialect specific information like information schema
  122. and columnames in information_schema.tables and
  123. information_schema.columns
  124. For ibm databases, information_schema is set to syscat,
  125. else it is set to information_schema
  126. If these default values do not exist in the given database,
  127. the output of the method is set to None
  128. :return: dictionary with information_schema, schema_col,
  129. table_col, column_col, default_schema
  130. '''
  131. db_metadata = {}
  132. if 'ibm' in self._db_uri:
  133. db_metadata['information_schema'] = 'syscat'
  134. db_metadata['schema_col'] = 'tabschema'
  135. db_metadata['table_col'] = 'tabname'
  136. db_metadata['column_col'] = 'colname'
  137. db_metadata['default_schema'] =\
  138. self._connection_params['user'].upper()
  139. else:
  140. db_metadata['information_schema'] = 'information_schema'
  141. db_metadata['schema_col'] = 'TABLE_SCHEMA'
  142. db_metadata['table_col'] = 'TABLE_NAME'
  143. db_metadata['column_col'] = 'COLUMN_NAME'
  144. db_metadata['default_schema'] =\
  145. self._connection_params['db']
  146. # check if it worked to create metadata
  147. try:
  148. query = """SELECT *
  149. FROM {}.tables
  150. LIMIT 1
  151. """.format(db_metadata['information_schema'])
  152. self.execute(query)
  153. except Exception as e:
  154. self._log.error(e)
  155. db_metadata = None
  156. return db_metadata
  157. def execute(self, query):
  158. '''
  159. Executes an sql-queries.
  160. Remark: queries like CREATE, DROP, SELECT work
  161. for majority of sqlalchemy dialects.
  162. queries like SHOW TABLES, LOAD DATA, and using
  163. INFORMATION_SCHEMA are mysql specific and might
  164. not exist in a different dialect.
  165. :param str query:
  166. '''
  167. connection = self._engine.connect()
  168. transaction = connection.begin()
  169. errors = []
  170. # in the case of multi-query execute each query
  171. for sub_query in sqlparse.split(query):
  172. if len(sub_query) > 0:
  173. try:
  174. connection.execute(sub_query, multi=True)
  175. except Exception as e:
  176. errors.append(str(e))
  177. if len(errors) > 0:
  178. err = ('Could not execute some of the queries. '
  179. 'Obtained exceptions: {}'
  180. .format('\n'.join(errors)))
  181. self._log.error(err)
  182. raise Exception(err)
  183. transaction.commit()
  184. connection.close()
  185. def execute_query_from_file(self, filename: str):
  186. '''
  187. '''
  188. with open(filename, 'r') as f:
  189. query = f.read()
  190. self.execute(query)
  191. def get_tablenames(self, schema: str = None, query: str = None):
  192. '''
  193. '''
  194. if (self._db_metadata is None) and (query is None):
  195. raise Exception('Please specify the query')
  196. else:
  197. try:
  198. if query is None:
  199. schema_or_default_schema =\
  200. self._db_metadata['default_schema']\
  201. if schema is None else schema
  202. query = """SELECT DISTINCT {0}
  203. FROM {1}.tables
  204. WHERE {2} = '{3}'
  205. """.format(
  206. self._db_metadata['table_col'],
  207. self._db_metadata['information_schema'],
  208. self._db_metadata['schema_col'],
  209. schema_or_default_schema)
  210. tables = self.read_sql_to_dataframe(query).iloc[:, 0].tolist()
  211. return tables
  212. except Exception as e:
  213. err = ("Could not get tablenames"
  214. "Finished with error {}".format(e))
  215. self._log.error(err)
  216. raise Exception(err)
  217. def check_if_table_exists(self, tablename: str,
  218. schema: str = None,
  219. query: str = None) -> bool:
  220. '''
  221. Tries to retrieve table information from database with given query.
  222. If this does not work, tries to select one row from the given table,
  223. if this fails, assumes that the table does not exist.
  224. :param str tablename:
  225. :param str schema:
  226. :param str query: if not specified, tries to find
  227. tablename in information_schema specified in _db_metadata.
  228. :return: if the table exists or not
  229. :rtype: bool
  230. '''
  231. if self._is_case_insensitive:
  232. tablename = tablename.upper()
  233. try:
  234. tablenames = self.get_tablenames(schema=schema, query=query)
  235. table_exists = (tablename in tablenames)
  236. except Exception as e:
  237. self._log.warning(('Could not execute query to retrieve table '
  238. 'information. Trying to execute a'
  239. 'select statement. '
  240. 'Got exeption {}').format(e))
  241. try:
  242. query = """SELECT *
  243. FROM {0}{1}
  244. LIMIT 1
  245. """.format('' if schema is None else schema + '.',
  246. tablename)
  247. self.execute(query)
  248. table_exists = True
  249. except Exception as e:
  250. self._log.warning(('Failed to select from {0}. '
  251. 'Finished with error {1}'
  252. 'Conclusion: table does not exist')
  253. .format(tablename, e))
  254. table_exists = False
  255. return table_exists
  256. def create_schema(self, schema: str, query: str = None):
  257. '''
  258. Creates a schema if it does not exist, else does nothing
  259. :param str schema:
  260. :param str query: if None trying to read schemas from
  261. information_schema specified in db_metadata
  262. '''
  263. if (query is None):
  264. if self._db_metadata is None:
  265. raise Exception('Please specify query')
  266. else:
  267. query = """SELECT DISTINCT {0}
  268. FROM {1}.tables""".format(
  269. self._db_metadata['schema_col'],
  270. self._db_metadata['information_schema'])
  271. try:
  272. schemas = self.read_sql_to_dataframe(query).iloc[:, 0].tolist()
  273. except Exception as e:
  274. err = ("Could not retrieve the list of schemas"
  275. "from the database. Finished with error {}"
  276. .format(e))
  277. self._log.error(err)
  278. raise Exception(err)
  279. if schema not in schemas:
  280. self.execute("CREATE SCHEMA {}".format(schema))
  281. def drop_table_if_exists(self, tablename: str,
  282. schema: str = None,
  283. query: str = None):
  284. '''
  285. :param str tablename:
  286. :param str schema:
  287. :param str query: if not specified, default value is "DROP TABLE"
  288. '''
  289. if self._is_case_insensitive:
  290. tablename = tablename.upper()
  291. schema = '' if schema is None else schema + '.'
  292. if query is None:
  293. query = "DROP TABLE {0}{1};".format(schema, tablename)
  294. try:
  295. if self.check_if_table_exists(tablename):
  296. self.execute(query)
  297. except Exception as e:
  298. err = ("Could not drop the table {0} ."
  299. "Finished with error {1}"
  300. .format(tablename, e))
  301. self._log.error(err)
  302. raise Exception(err)
  303. def get_column_names(self, tablename: str,
  304. schema: str = None,
  305. query: str = None) -> list:
  306. '''
  307. Tries to retrieve column information from database with given query.
  308. If this does not work, tries to select one row from the given table.
  309. :param str tablename:
  310. :param str schema:
  311. :param str query: if not specified, tries to select column
  312. names in the information_schema specified in db_metadata
  313. '''
  314. if self._is_case_insensitive:
  315. tablename = tablename.upper()
  316. if not self.check_if_table_exists(tablename=tablename,
  317. schema=schema):
  318. err = "Table {} does not exist".format(tablename)
  319. self._log.error(err)
  320. raise Exception(err)
  321. try:
  322. if query is None:
  323. if self._db_metadata is None:
  324. raise Exception('Please specify the query')
  325. else:
  326. schema_or_default_schema =\
  327. self._db_metadata['default_schema']\
  328. if schema is None else schema
  329. query = """SELECT DISTINCT {0}
  330. FROM {1}.columns
  331. WHERE {2} = '{3}'
  332. AND {4} = '{5}'
  333. """.format(
  334. self._db_metadata['column_col'],
  335. self._db_metadata['information_schema'],
  336. self._db_metadata['schema_col'],
  337. schema_or_default_schema,
  338. self._db_metadata['table_col'],
  339. tablename)
  340. colnames = [c.lower() for c in
  341. self.read_sql_to_dataframe(query).iloc[:, 0].tolist()]
  342. except Exception as e:
  343. self._log.warn((
  344. 'Could not select columns from '
  345. 'informational schema. Trying to '
  346. 'load the table into a dataframe and selec column names.'
  347. 'Obtained exception {}').format(e))
  348. query = """SELECT *
  349. FROM {0}{1}
  350. LIMIT 1
  351. """.format('' if schema is None else schema + '.',
  352. tablename)
  353. data = self.execute(query)
  354. colnames = data.columns.tolist()
  355. return colnames
  356. def load_csv_to_db(self, filename: str,
  357. tablename: str,
  358. schema: str = None,
  359. query: str = None,
  360. **kwargs):
  361. '''
  362. Tries to load data from csv file to database with a given query.
  363. If this does not work, tries to load data from csv to a
  364. pandas dataframe first, and then write it to the database.
  365. :param str filename:
  366. :param str tablename:
  367. :param str schema:
  368. :param str query: if not specified, tries to use
  369. LOAD DATA LOCAL INFILE query
  370. '''
  371. if not self.check_if_table_exists(tablename=tablename,
  372. schema=schema):
  373. err = ('Table {} test does not exit.'
  374. 'Please create it first').format(tablename)
  375. self._log.error(err)
  376. raise Exception(err)
  377. else:
  378. try:
  379. if query is None:
  380. query = """LOAD DATA LOCAL INFILE '{0}'
  381. INTO TABLE {1}{2}
  382. COLUMNS TERMINATED BY ','
  383. OPTIONALLY ENCLOSED BY '"'
  384. LINES TERMINATED BY '\r\n'
  385. IGNORE 1 LINES
  386. ({3})
  387. ;""".format(
  388. filename,
  389. '' if schema is None else schema + '.',
  390. tablename,
  391. ','.join(self.get_column_names(tablename)))
  392. self.execute(query)
  393. except Exception as e:
  394. err = ("Could not load the file {0} "
  395. "to the table {1} ."
  396. "Finished with error {2}")\
  397. .format(filename, tablename, e)
  398. self._log.error(err)
  399. raise Exception(err)
  400. def read_sql_to_dataframe(self, query: str, **read_sql_kwargs):
  401. '''
  402. :param str query: normally a SELECT sql statement
  403. :param read_sql_kwargs: additional arguments to pandas read_sql method
  404. :return: selected data
  405. :rtype: DataFrame
  406. '''
  407. try:
  408. connection = self._engine.connect()
  409. data = pd.read_sql(sql=query,
  410. con=connection,
  411. **read_sql_kwargs)
  412. connection.close()
  413. return data
  414. except Exception as e:
  415. err = ("Could not read the query to a dataframe. "
  416. "Finished with error {}").format(e)
  417. self._log.error(err)
  418. raise Exception(err)
  419. def read_table(self, tablename: str,
  420. schema: str = None,
  421. **read_sql_kwargs):
  422. '''
  423. :param str tablename:
  424. :param str schema:
  425. :param read_sql_kwargs: additional arguments to pands read_sql_method
  426. :return: selected table
  427. :rtype: DataFrame
  428. '''
  429. schema = '' if schema is None else schema + '.'
  430. try:
  431. return self.read_sql_to_dataframe(
  432. query="SELECT * FROM {0}{1};".format(schema, tablename),
  433. **read_sql_kwargs)
  434. except Exception as e:
  435. err = ("Could not read the table {0} to a dataframe. "
  436. "Finished with error {1}").format(tablename, e)
  437. self._log.error(err)
  438. raise Exception(err)
  439. def append_to_table(self, data: pd.DataFrame,
  440. tablename: str,
  441. schema: str = None,
  442. to_sql_kwargs={'index': False}):
  443. '''
  444. :param DataFrame data: data to append
  445. :param str tablename: table where data is appended
  446. :param str schema:
  447. :param dict to_sql_kwargs: additional arguments to pandas to_sql method
  448. '''
  449. if schema is not None:
  450. self.create_schema(schema)
  451. try:
  452. connection = self._engine.connect()
  453. if self.check_if_table_exists(tablename=tablename, schema=schema):
  454. data.to_sql(name=tablename,
  455. schema=schema,
  456. con=connection,
  457. if_exists='append',
  458. **to_sql_kwargs)
  459. else:
  460. self.overwrite_table(data=data,
  461. tablename=tablename,
  462. schema=schema,
  463. to_sql_kwargs=to_sql_kwargs)
  464. connection.close()
  465. except Exception as e:
  466. err = ("Could not append data to the table {0}. "
  467. "Finished with error {1}").format(tablename, e)
  468. self._log.error(err)
  469. raise Exception(err)
  470. def overwrite_table(self, data: pd.DataFrame,
  471. tablename: str,
  472. schema: str = None,
  473. to_sql_kwargs={'index': False}):
  474. '''
  475. :param DataFrame data: data to write to dabase
  476. :param str tablename: table where data is written
  477. :param str schema:
  478. :param to_sql_kwargs: additional arguments to pandas to_sql method
  479. '''
  480. if schema is not None:
  481. self.create_schema(schema)
  482. try:
  483. connection = self._engine.connect()
  484. data.to_sql(name=tablename,
  485. schema=schema,
  486. con=connection,
  487. if_exists='replace',
  488. **to_sql_kwargs)
  489. connection.close()
  490. except Exception as e:
  491. err = ("Could overwrite the table {0}. "
  492. "Finished with error {1}").format(tablename, e)
  493. self._log.error(err)
  494. raise Exception(err)
  495. def draw_er_diagram_from_db(self, diagram_path: str = None,
  496. schema: str = None,
  497. include_tables: list = None):
  498. '''
  499. '''
  500. if diagram_path is None:
  501. diagram_path = "erd.png"
  502. else:
  503. diagram_dir = os.path.dirname(diagram_path)
  504. if diagram_dir != "":
  505. os.makedirs(diagram_dir, exist_ok=True)
  506. import eralchemy
  507. eralchemy.render_er(self._db_uri,
  508. diagram_path,
  509. schema=schema,
  510. include_tables=include_tables)
  511. def dispose_engine(self):
  512. try:
  513. self._engine.dispose()
  514. except Exception as e:
  515. self._log.log_and_raise_error(('An error occured when trying to dispose the SQL engine. Error: {}').format(e))