SQLHandler.py 21 KB

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