SQLHandler.py 22 KB

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