SQLHandler.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. #class SQLHandlerPool():
  19. '''
  20. '''
  21. def __init__(self, size: int = 1):
  22. self._size = size
  23. self._log = Log(name='SQLHandlerPool')
  24. self._sql_handlers = [SQLHandler() for _ in range(size)]
  25. def aquire(self):
  26. while not self._sql_handlers:
  27. self._sql_handlers = [SQLHandler() for _ in range(self._size)]
  28. self._log.warning("Ran out of SQL handlers, 10 more have been added. Are you sure you've returned yours?")
  29. return self._sql_handlers.pop()
  30. def release(self, mongodb_handler):
  31. if len(self._sql_handlers) < self._size:
  32. self._sql_handlers.append(mongodb_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. @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. # in the case of multi-query execute each query
  169. for sub_query in sqlparse.split(query):
  170. if len(sub_query) > 0:
  171. try:
  172. connection.execute(sub_query, multi=True)
  173. except Exception as e:
  174. errors.append(str(e))
  175. if len(errors) > 0:
  176. err = ('Could not execute some of the queries. '
  177. 'Obtained exceptions: {}'
  178. .format('\n'.join(errors)))
  179. self._log.error(err)
  180. raise Exception(err)
  181. transaction.commit()
  182. connection.close()
  183. def execute_query_from_file(self, filename: str):
  184. '''
  185. '''
  186. with open(filename, 'r') as f:
  187. query = f.read()
  188. self.execute(query)
  189. def get_tablenames(self, schema: str = None, query: str = None):
  190. '''
  191. '''
  192. if (self._db_metadata is None) and (query is None):
  193. raise Exception('Please specify the query')
  194. else:
  195. try:
  196. if query is None:
  197. schema_or_default_schema =\
  198. self._db_metadata['default_schema']\
  199. if schema is None else schema
  200. query = """SELECT DISTINCT {0}
  201. FROM {1}.tables
  202. WHERE {2} = '{3}'
  203. """.format(
  204. self._db_metadata['table_col'],
  205. self._db_metadata['information_schema'],
  206. self._db_metadata['schema_col'],
  207. schema_or_default_schema)
  208. tables = self.read_sql_to_dataframe(query).iloc[:, 0].tolist()
  209. return tables
  210. except Exception as e:
  211. err = ("Could not get tablenames"
  212. "Finished with error {}".format(e))
  213. self._log.error(err)
  214. raise Exception(err)
  215. def check_if_table_exists(self, tablename: str,
  216. schema: str = None,
  217. query: str = None) -> bool:
  218. '''
  219. Tries to retrieve table information from database with given query.
  220. If this does not work, tries to select one row from the given table,
  221. if this fails, assumes that the table does not exist.
  222. :param str tablename:
  223. :param str schema:
  224. :param str query: if not specified, tries to find
  225. tablename in information_schema specified in _db_metadata.
  226. :return: if the table exists or not
  227. :rtype: bool
  228. '''
  229. if self._is_case_insensitive:
  230. tablename = tablename.upper()
  231. try:
  232. tablenames = self.get_tablenames(schema=schema, query=query)
  233. table_exists = (tablename in tablenames)
  234. except Exception as e:
  235. self._log.warning(('Could not execute query to retrieve table '
  236. 'information. Trying to execute a'
  237. 'select statement. '
  238. 'Got exeption {}').format(e))
  239. try:
  240. query = """SELECT *
  241. FROM {0}{1}
  242. LIMIT 1
  243. """.format('' if schema is None else schema + '.',
  244. tablename)
  245. self.execute(query)
  246. table_exists = True
  247. except Exception as e:
  248. self._log.warning(('Failed to select from {0}. '
  249. 'Finished with error {1}'
  250. 'Conclusion: table does not exist')
  251. .format(tablename, e))
  252. table_exists = False
  253. return table_exists
  254. def create_schema(self, schema: str, query: str = None):
  255. '''
  256. Creates a schema if it does not exist, else does nothing
  257. :param str schema:
  258. :param str query: if None trying to read schemas from
  259. information_schema specified in db_metadata
  260. '''
  261. if (query is None):
  262. if self._db_metadata is None:
  263. raise Exception('Please specify query')
  264. else:
  265. query = """SELECT DISTINCT {0}
  266. FROM {1}.tables""".format(
  267. self._db_metadata['schema_col'],
  268. self._db_metadata['information_schema'])
  269. try:
  270. schemas = self.read_sql_to_dataframe(query).iloc[:, 0].tolist()
  271. except Exception as e:
  272. err = ("Could not retrieve the list of schemas"
  273. "from the database. Finished with error {}"
  274. .format(e))
  275. self._log.error(err)
  276. raise Exception(err)
  277. if schema not in schemas:
  278. self.execute("CREATE SCHEMA {}".format(schema))
  279. def drop_table_if_exists(self, tablename: str,
  280. schema: str = None,
  281. query: str = None):
  282. '''
  283. :param str tablename:
  284. :param str schema:
  285. :param str query: if not specified, default value is "DROP TABLE"
  286. '''
  287. if self._is_case_insensitive:
  288. tablename = tablename.upper()
  289. schema = '' if schema is None else schema + '.'
  290. if query is None:
  291. query = "DROP TABLE {0}{1};".format(schema, tablename)
  292. try:
  293. if self.check_if_table_exists(tablename):
  294. self.execute(query)
  295. except Exception as e:
  296. err = ("Could not drop the table {0} ."
  297. "Finished with error {1}"
  298. .format(tablename, e))
  299. self._log.error(err)
  300. raise Exception(err)
  301. def get_column_names(self, tablename: str,
  302. schema: str = None,
  303. query: str = None) -> list:
  304. '''
  305. Tries to retrieve column information from database with given query.
  306. If this does not work, tries to select one row from the given table.
  307. :param str tablename:
  308. :param str schema:
  309. :param str query: if not specified, tries to select column
  310. names in the information_schema specified in db_metadata
  311. '''
  312. if self._is_case_insensitive:
  313. tablename = tablename.upper()
  314. if not self.check_if_table_exists(tablename=tablename,
  315. schema=schema):
  316. err = "Table {} does not exist".format(tablename)
  317. self._log.error(err)
  318. raise Exception(err)
  319. try:
  320. if query is None:
  321. if self._db_metadata is None:
  322. raise Exception('Please specify the query')
  323. else:
  324. schema_or_default_schema =\
  325. self._db_metadata['default_schema']\
  326. if schema is None else schema
  327. query = """SELECT DISTINCT {0}
  328. FROM {1}.columns
  329. WHERE {2} = '{3}'
  330. AND {4} = '{5}'
  331. """.format(
  332. self._db_metadata['column_col'],
  333. self._db_metadata['information_schema'],
  334. self._db_metadata['schema_col'],
  335. schema_or_default_schema,
  336. self._db_metadata['table_col'],
  337. tablename)
  338. colnames = [c.lower() for c in
  339. self.read_sql_to_dataframe(query).iloc[:, 0].tolist()]
  340. except Exception as e:
  341. self._log.warn((
  342. 'Could not select columns from '
  343. 'informational schema. Trying to '
  344. 'load the table into a dataframe and selec column names.'
  345. 'Obtained exception {}').format(e))
  346. query = """SELECT *
  347. FROM {0}{1}
  348. LIMIT 1
  349. """.format('' if schema is None else schema + '.',
  350. tablename)
  351. data = self.execute(query)
  352. colnames = data.columns.tolist()
  353. return colnames
  354. def load_csv_to_db(self, filename: str,
  355. tablename: str,
  356. schema: str = None,
  357. query: str = None,
  358. **kwargs):
  359. '''
  360. Tries to load data from csv file to database with a given query.
  361. If this does not work, tries to load data from csv to a
  362. pandas dataframe first, and then write it to the database.
  363. :param str filename:
  364. :param str tablename:
  365. :param str schema:
  366. :param str query: if not specified, tries to use
  367. LOAD DATA LOCAL INFILE query
  368. '''
  369. if not self.check_if_table_exists(tablename=tablename,
  370. schema=schema):
  371. err = ('Table {} test does not exit.'
  372. 'Please create it first').format(tablename)
  373. self._log.error(err)
  374. raise Exception(err)
  375. else:
  376. try:
  377. if query is None:
  378. query = """LOAD DATA LOCAL INFILE '{0}'
  379. INTO TABLE {1}{2}
  380. COLUMNS TERMINATED BY ','
  381. OPTIONALLY ENCLOSED BY '"'
  382. LINES TERMINATED BY '\r\n'
  383. IGNORE 1 LINES
  384. ({3})
  385. ;""".format(
  386. filename,
  387. '' if schema is None else schema + '.',
  388. tablename,
  389. ','.join(self.get_column_names(tablename)))
  390. self.execute(query)
  391. except Exception as e:
  392. err = ("Could not load the file {0} "
  393. "to the table {1} ."
  394. "Finished with error {2}")\
  395. .format(filename, tablename, e)
  396. self._log.error(err)
  397. raise Exception(err)
  398. def read_sql_to_dataframe(self, query: str, **read_sql_kwargs):
  399. '''
  400. :param str query: normally a SELECT sql statement
  401. :param read_sql_kwargs: additional arguments to pandas read_sql method
  402. :return: selected data
  403. :rtype: DataFrame
  404. '''
  405. try:
  406. connection = self._engine.connect()
  407. data = pd.read_sql(sql=query,
  408. con=connection,
  409. **read_sql_kwargs)
  410. connection.close()
  411. return data
  412. except Exception as e:
  413. err = ("Could not read the query to a dataframe. "
  414. "Finished with error {}").format(e)
  415. self._log.error(err)
  416. raise Exception(err)
  417. def read_table(self, tablename: str,
  418. schema: str = None,
  419. **read_sql_kwargs):
  420. '''
  421. :param str tablename:
  422. :param str schema:
  423. :param read_sql_kwargs: additional arguments to pands read_sql_method
  424. :return: selected table
  425. :rtype: DataFrame
  426. '''
  427. schema = '' if schema is None else schema + '.'
  428. try:
  429. return self.read_sql_to_dataframe(
  430. query="SELECT * FROM {0}{1};".format(schema, tablename),
  431. **read_sql_kwargs)
  432. except Exception as e:
  433. err = ("Could not read the table {0} to a dataframe. "
  434. "Finished with error {1}").format(tablename, e)
  435. self._log.error(err)
  436. raise Exception(err)
  437. def append_to_table(self, data: pd.DataFrame,
  438. tablename: str,
  439. schema: str = None,
  440. to_sql_kwargs={'index': False}):
  441. '''
  442. :param DataFrame data: data to append
  443. :param str tablename: table where data is appended
  444. :param str schema:
  445. :param dict to_sql_kwargs: additional arguments to pandas to_sql method
  446. '''
  447. if schema is not None:
  448. self.create_schema(schema)
  449. try:
  450. connection = self._engine.connect()
  451. if self.check_if_table_exists(tablename=tablename, schema=schema):
  452. data.to_sql(name=tablename,
  453. schema=schema,
  454. con=connection,
  455. if_exists='append',
  456. **to_sql_kwargs)
  457. else:
  458. self.overwrite_table(data=data,
  459. tablename=tablename,
  460. schema=schema,
  461. to_sql_kwargs=to_sql_kwargs)
  462. connection.close()
  463. except Exception as e:
  464. err = ("Could not append data to the table {0}. "
  465. "Finished with error {1}").format(tablename, e)
  466. self._log.error(err)
  467. raise Exception(err)
  468. def overwrite_table(self, data: pd.DataFrame,
  469. tablename: str,
  470. schema: str = None,
  471. to_sql_kwargs={'index': False}):
  472. '''
  473. :param DataFrame data: data to write to dabase
  474. :param str tablename: table where data is written
  475. :param str schema:
  476. :param to_sql_kwargs: additional arguments to pandas to_sql method
  477. '''
  478. if schema is not None:
  479. self.create_schema(schema)
  480. try:
  481. connection = self._engine.connect()
  482. data.to_sql(name=tablename,
  483. schema=schema,
  484. con=connection,
  485. if_exists='replace',
  486. **to_sql_kwargs)
  487. connection.close()
  488. except Exception as e:
  489. err = ("Could overwrite the table {0}. "
  490. "Finished with error {1}").format(tablename, e)
  491. self._log.error(err)
  492. raise Exception(err)
  493. def draw_er_diagram_from_db(self, diagram_path: str = None,
  494. schema: str = None,
  495. include_tables: list = None):
  496. '''
  497. '''
  498. if diagram_path is None:
  499. diagram_path = "erd.png"
  500. else:
  501. diagram_dir = os.path.dirname(diagram_path)
  502. if diagram_dir != "":
  503. os.makedirs(diagram_dir, exist_ok=True)
  504. import eralchemy
  505. eralchemy.render_er(self._db_uri,
  506. diagram_path,
  507. schema=schema,
  508. include_tables=include_tables)