SQLHandler.py 22 KB

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