sql.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. """
  2. This file is intended to perform read/writes against an SQL database such as PostgreSQL, Redshift, Mysql, MsSQL ...
  3. LICENSE (MIT)
  4. Copyright 2016-2020, The Phi Technology LLC
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  6. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  7. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  8. @TODO:
  9. - Migrate SQLite to SQL hierarchy
  10. - Include Write in Chunks from pandas
  11. """
  12. import psycopg2 as pg
  13. import mysql.connector as my
  14. import sys
  15. import sqlalchemy
  16. if sys.version_info[0] > 2 :
  17. from transport.common import Reader, Writer #, factory
  18. else:
  19. from common import Reader,Writer
  20. import json
  21. from google.oauth2 import service_account
  22. from google.cloud import bigquery as bq
  23. from multiprocessing import Lock, RLock
  24. import pandas as pd
  25. import numpy as np
  26. import nzpy as nz #--- netezza drivers
  27. import sqlite3
  28. import copy
  29. import os
  30. import time
  31. class SQLRW :
  32. lock = RLock()
  33. MAX_CHUNK = 2000000
  34. DRIVERS = {"postgresql":pg,"redshift":pg,"mysql":my,"mariadb":my,"netezza":nz}
  35. REFERENCE = {
  36. "netezza":{"port":5480,"handler":nz,"dtype":"VARCHAR(512)"},
  37. "postgresql":{"port":5432,"handler":pg,"dtype":"VARCHAR"},
  38. "redshift":{"port":5432,"handler":pg,"dtype":"VARCHAR"},
  39. "mysql":{"port":3360,"handler":my,"dtype":"VARCHAR(256)"},
  40. "mariadb":{"port":3360,"handler":my,"dtype":"VARCHAR(256)"},
  41. }
  42. def __init__(self,**_args):
  43. _info = {}
  44. _info['dbname'] = _args['db'] if 'db' in _args else _args['database']
  45. self.table = _args['table'] if 'table' in _args else None
  46. self.fields = _args['fields'] if 'fields' in _args else []
  47. self.schema = _args['schema'] if 'schema' in _args else ''
  48. self._chunks = 1 if 'chunks' not in _args else int(_args['chunks'])
  49. self._provider = _args['provider'] if 'provider' in _args else None
  50. # _info['host'] = 'localhost' if 'host' not in _args else _args['host']
  51. # _info['port'] = SQLWriter.REFERENCE[_provider]['port'] if 'port' not in _args else _args['port']
  52. _info['host'] = _args['host'] if 'host' in _args else ''
  53. _info['port'] = _args['port'] if 'port' in _args else ''
  54. # if 'host' in _args :
  55. # _info['host'] = 'localhost' if 'host' not in _args else _args['host']
  56. # # _info['port'] = SQLWriter.PROVIDERS[_args['provider']] if 'port' not in _args else _args['port']
  57. # _info['port'] = SQLWriter.REFERENCE[_provider]['port'] if 'port' not in _args else _args['port']
  58. self.lock = False if 'lock' not in _args else _args['lock']
  59. if 'username' in _args or 'user' in _args:
  60. key = 'username' if 'username' in _args else 'user'
  61. _info['user'] = _args[key]
  62. _info['password'] = _args['password'] if 'password' in _args else ''
  63. if 'auth_file' in _args :
  64. _auth = json.loads( open(_args['auth_file']).read() )
  65. key = 'username' if 'username' in _auth else 'user'
  66. _info['user'] = _auth[key]
  67. _info['password'] = _auth['password'] if 'password' in _auth else ''
  68. _info['host'] = _auth['host'] if 'host' in _auth else _info['host']
  69. _info['port'] = _auth['port'] if 'port' in _auth else _info['port']
  70. if 'database' in _auth:
  71. _info['dbname'] = _auth['database']
  72. self.table = _auth['table'] if 'table' in _auth else self.table
  73. #
  74. # We need to load the drivers here to see what we are dealing with ...
  75. # _handler = SQLWriter.REFERENCE[_provider]['handler']
  76. _handler = _args['driver'] #-- handler to the driver
  77. self._dtype = _args['default']['type'] if 'default' in _args and 'type' in _args['default'] else 'VARCHAR(256)'
  78. # self._provider = _args['provider']
  79. # self._dtype = SQLWriter.REFERENCE[_provider]['dtype'] if 'dtype' not in _args else _args['dtype']
  80. # self._provider = _provider
  81. if _handler == nz :
  82. _info['database'] = _info['dbname']
  83. _info['securityLevel'] = 0
  84. del _info['dbname']
  85. if _handler == my :
  86. _info['database'] = _info['dbname']
  87. del _info['dbname']
  88. if _handler == sqlite3 :
  89. _info = {'path':_info['dbname'],'isolation_level':'IMMEDIATE'}
  90. if _handler != sqlite3 :
  91. self.conn = _handler.connect(**_info)
  92. else:
  93. self.conn = _handler.connect(_info['path'],isolation_level='IMMEDIATE')
  94. self._engine = _args['sqlalchemy'] if 'sqlalchemy' in _args else None
  95. def meta(self,**_args):
  96. schema = []
  97. try:
  98. if self._engine :
  99. table = _args['table'] if 'table' in _args else self.table
  100. if sqlalchemy.__version__.startswith('1.') :
  101. _m = sqlalchemy.MetaData(bind=self._engine)
  102. _m.reflect()
  103. else:
  104. _m = sqlalchemy.MetaData()
  105. _m.reflect(bind=self._engine)
  106. schema = [{"name":_attr.name,"type":str(_attr.type)} for _attr in _m.tables[table].columns]
  107. #
  108. # Some house keeping work
  109. _m = {'BIGINT':'INTEGER','TEXT':'STRING','DOUBLE_PRECISION':'FLOAT','NUMERIC':'FLOAT','DECIMAL':'FLOAT','REAL':'FLOAT'}
  110. for _item in schema :
  111. if _item['type'] in _m :
  112. _item['type'] = _m[_item['type']]
  113. except Exception as e:
  114. print (e)
  115. pass
  116. return schema
  117. def _tablename(self,name) :
  118. return self.schema +'.'+name if self.schema not in [None, ''] and '.' not in name else name
  119. def has(self,**_args):
  120. return self.meta(**_args)
  121. # found = False
  122. # try:
  123. # table = self._tablename(_args['table'])if 'table' in _args else self._tablename(self.table)
  124. # sql = "SELECT * FROM :table LIMIT 1".replace(":table",table)
  125. # if self._engine :
  126. # _conn = self._engine.connect()
  127. # else:
  128. # _conn = self.conn
  129. # found = pd.read_sql(sql,_conn).shape[0]
  130. # found = True
  131. # except Exception as e:
  132. # print (e)
  133. # pass
  134. # finally:
  135. # if not self._engine :
  136. # _conn.close()
  137. # return found
  138. def isready(self):
  139. _sql = "SELECT * FROM :table LIMIT 1".replace(":table",self.table)
  140. try:
  141. _conn = self.conn if not hasattr(self,'_engine') else self._engine
  142. return pd.read_sql(_sql,_conn).columns.tolist()
  143. except Exception as e:
  144. pass
  145. return False
  146. def apply(self,_sql):
  147. """
  148. This function applies a command and/or a query against the current relational data-store
  149. :param _sql insert/select statement
  150. @TODO: Store procedure calls
  151. """
  152. #
  153. _out = None
  154. try:
  155. if _sql.lower().startswith('select') :
  156. _conn = self._engine if self._engine else self.conn
  157. return pd.read_sql(_sql,_conn)
  158. else:
  159. # Executing a command i.e no expected return values ...
  160. cursor = self.conn.cursor()
  161. cursor.execute(_sql)
  162. self.conn.commit()
  163. except Exception as e :
  164. print (e)
  165. finally:
  166. if not self._engine :
  167. self.conn.commit()
  168. # cursor.close()
  169. def close(self):
  170. try:
  171. self.conn.close()
  172. except Exception as error :
  173. print (error)
  174. pass
  175. class SQLReader(SQLRW,Reader) :
  176. def __init__(self,**_args):
  177. super().__init__(**_args)
  178. def read(self,**_args):
  179. if 'sql' in _args :
  180. _sql = (_args['sql'])
  181. else:
  182. if 'table' in _args :
  183. table = _args['table']
  184. else:
  185. table = self.table
  186. # table = self.table if self.table is not None else _args['table']
  187. _sql = "SELECT :fields FROM "+self._tablename(table)
  188. if 'filter' in _args :
  189. _sql = _sql +" WHERE "+_args['filter']
  190. if 'fields' in _args :
  191. _fields = _args['fields']
  192. else:
  193. _fields = '*' if not self.fields else ",".join(self.fields)
  194. _sql = _sql.replace(":fields",_fields)
  195. #
  196. # At this point we have a query we can execute gracefully
  197. if 'limit' in _args :
  198. _sql = _sql + " LIMIT "+str(_args['limit'])
  199. #
  200. # @TODO:
  201. # It is here that we should inspect to see if there are any pre/post conditions
  202. #
  203. return self.apply(_sql)
  204. def close(self) :
  205. try:
  206. self.conn.close()
  207. except Exception as error :
  208. print (error)
  209. pass
  210. class SQLWriter(SQLRW,Writer):
  211. def __init__(self,**_args) :
  212. super().__init__(**_args)
  213. #
  214. # In the advent that data typing is difficult to determine we can inspect and perform a default case
  215. # This slows down the process but improves reliability of the data
  216. # NOTE: Proper data type should be set on the target system if their source is unclear.
  217. self._cast = False if 'cast' not in _args else _args['cast']
  218. def init(self,fields=None):
  219. # if not fields :
  220. # try:
  221. # table = self._tablename(self.table)
  222. # self.fields = pd.read_sql_query("SELECT * FROM :table LIMIT 1".replace(":table",table),self.conn).columns.tolist()
  223. # except Exception as e:
  224. # pass
  225. # finally:
  226. # pass
  227. # else:
  228. self.fields = fields;
  229. def make(self,**_args):
  230. table = self._tablename(self.table) if 'table' not in _args else self._tablename(_args['table'])
  231. if 'fields' in _args :
  232. fields = _args['fields']
  233. # table = self._tablename(self.table)
  234. sql = " ".join(["CREATE TABLE",table," (", ",".join([ name +' '+ self._dtype for name in fields]),")"])
  235. else:
  236. schema = _args['schema'] if 'schema' in _args else []
  237. _map = _args['map'] if 'map' in _args else {}
  238. sql = [] # ["CREATE TABLE ",_args['table'],"("]
  239. for _item in schema :
  240. _type = _item['type']
  241. if _type in _map :
  242. _type = _map[_type]
  243. sql = sql + [" " .join([_item['name'], ' ',_type])]
  244. sql = ",".join(sql)
  245. # table = self._tablename(_args['table'])
  246. sql = ["CREATE TABLE ",table,"( ",sql," )"]
  247. sql = " ".join(sql)
  248. cursor = self.conn.cursor()
  249. try:
  250. cursor.execute(sql)
  251. except Exception as e :
  252. print (e)
  253. # print (sql)
  254. pass
  255. finally:
  256. # cursor.close()
  257. self.conn.commit()
  258. pass
  259. def write(self,info,**_args):
  260. """
  261. :param info writes a list of data to a given set of fields
  262. """
  263. # inspect = False if 'inspect' not in _args else _args['inspect']
  264. # cast = False if 'cast' not in _args else _args['cast']
  265. # if not self.fields :
  266. # if type(info) == list :
  267. # _fields = info[0].keys()
  268. # elif type(info) == dict :
  269. # _fields = info.keys()
  270. # elif type(info) == pd.DataFrame :
  271. # _fields = info.columns.tolist()
  272. # # _fields = info.keys() if type(info) == dict else info[0].keys()
  273. # # _fields = list (_fields)
  274. # self.init(_fields)
  275. try:
  276. table = _args['table'] if 'table' in _args else self.table
  277. #
  278. # In SQL, schema can stand for namespace or the structure of a table
  279. # In case we have a list, we are likely dealing with table structure
  280. #
  281. if 'schema' in _args :
  282. if type(_args['schema']) == str :
  283. self.schema = _args['schema'] if 'schema' in _args else self.schema
  284. elif type(_args['schema']) == list and len(_args['schema']) > 0 and not self.has(table=table):
  285. #
  286. # There is a messed up case when an empty array is passed (no table should be created)
  287. #
  288. self.make(table=table,schema=_args['schema'])
  289. pass
  290. # self.schema = _args['schema'] if 'schema' in _args else self.schema
  291. table = self._tablename(table)
  292. _sql = "INSERT INTO :table (:fields) VALUES (:values)".replace(":table",table) #.replace(":table",self.table).replace(":fields",_fields)
  293. if type(info) == list :
  294. _info = pd.DataFrame(info)
  295. elif type(info) == dict :
  296. _info = pd.DataFrame([info])
  297. else:
  298. _info = pd.DataFrame(info)
  299. if _info.shape[0] == 0 :
  300. return
  301. if self.lock :
  302. SQLRW.lock.acquire()
  303. #
  304. # we will adjust the chunks here in case we are not always sure of the
  305. if self._chunks == 1 and _info.shape[0] > SQLRW.MAX_CHUNK :
  306. self._chunks = 10
  307. _indexes = np.array_split(np.arange(_info.shape[0]),self._chunks)
  308. for i in _indexes :
  309. #
  310. # In case we have an invalid chunk ...
  311. if _info.iloc[i].shape[0] == 0 :
  312. continue
  313. #
  314. # We are enabling writing by chunks/batches because some persistent layers have quotas or limitations on volume of data
  315. if self._engine is not None:
  316. # pd.to_sql(_info,self._engine)
  317. if self.schema in ['',None] :
  318. rows = _info.iloc[i].to_sql(table,self._engine,if_exists='append',index=False)
  319. else:
  320. #
  321. # Writing with schema information ...
  322. rows = _info.iloc[i].to_sql(self.table,self._engine,schema=self.schema,if_exists='append',index=False)
  323. time.sleep(1)
  324. else:
  325. _fields = ",".join(self.fields)
  326. _sql = _sql.replace(":fields",_fields)
  327. values = ", ".join("?"*len(self.fields)) if self._provider == 'netezza' else ",".join(["%s" for name in self.fields])
  328. _sql = _sql.replace(":values",values)
  329. cursor = self.conn.cursor()
  330. cursor.executemany(_sql,_info.iloc[i].values.tolist())
  331. cursor.close()
  332. # cursor.commit()
  333. # self.conn.commit()
  334. except Exception as e:
  335. print(e)
  336. pass
  337. finally:
  338. if self._engine is None :
  339. self.conn.commit()
  340. if self.lock :
  341. SQLRW.lock.release()
  342. # cursor.close()
  343. pass
  344. def close(self):
  345. try:
  346. self.conn.close()
  347. finally:
  348. pass
  349. class BigQuery:
  350. def __init__(self,**_args):
  351. path = _args['service_key'] if 'service_key' in _args else _args['private_key']
  352. self.credentials = service_account.Credentials.from_service_account_file(path)
  353. self.dataset = _args['dataset'] if 'dataset' in _args else None
  354. self.path = path
  355. self.dtypes = _args['dtypes'] if 'dtypes' in _args else None
  356. self.table = _args['table'] if 'table' in _args else None
  357. self.client = bq.Client.from_service_account_json(self.path)
  358. def meta(self,**_args):
  359. """
  360. This function returns meta data for a given table or query with dataset/table properly formatted
  361. :param table name of the name WITHOUT including dataset
  362. :param sql sql query to be pulled,
  363. """
  364. table = _args['table'] if 'table' in _args else self.table
  365. try:
  366. if table :
  367. _dataset = self.dataset if 'dataset' not in _args else _args['dataset']
  368. sql = f"""SELECT column_name as name, data_type as type FROM {_dataset}.INFORMATION_SCHEMA.COLUMNS WHERE table_name = '{table}' """
  369. _info = {'credentials':self.credentials,'dialect':'standard'}
  370. return pd.read_gbq(sql,**_info).to_dict(orient='records')
  371. # return self.read(sql=sql).to_dict(orient='records')
  372. # ref = self.client.dataset(self.dataset).table(table)
  373. # _schema = self.client.get_table(ref).schema
  374. # return [{"name":_item.name,"type":_item.field_type,"description":( "" if not hasattr(_item,"description") else _item.description )} for _item in _schema]
  375. else :
  376. return []
  377. except Exception as e:
  378. return []
  379. def has(self,**_args):
  380. found = False
  381. try:
  382. _has = self.meta(**_args)
  383. found = _has is not None and len(_has) > 0
  384. except Exception as e:
  385. pass
  386. return found
  387. class BQReader(BigQuery,Reader) :
  388. def __init__(self,**_args):
  389. super().__init__(**_args)
  390. def apply(self,sql):
  391. return self.read(sql=sql)
  392. def read(self,**_args):
  393. SQL = None
  394. table = self.table if 'table' not in _args else _args['table']
  395. if 'sql' in _args :
  396. SQL = _args['sql']
  397. elif table:
  398. table = "".join(["`",table,"`"]) if '.' in table else "".join(["`:dataset.",table,"`"])
  399. SQL = "SELECT * FROM :table ".replace(":table",table)
  400. if not SQL :
  401. return None
  402. if SQL and 'limit' in _args:
  403. SQL += " LIMIT "+str(_args['limit'])
  404. if (':dataset' in SQL or ':DATASET' in SQL) and self.dataset:
  405. SQL = SQL.replace(':dataset',self.dataset).replace(':DATASET',self.dataset)
  406. _info = {'credentials':self.credentials,'dialect':'standard'}
  407. return pd.read_gbq(SQL,**_info) if SQL else None
  408. # return self.client.query(SQL).to_dataframe() if SQL else None
  409. class BQWriter(BigQuery,Writer):
  410. lock = Lock()
  411. def __init__(self,**_args):
  412. super().__init__(**_args)
  413. self.parallel = False if 'lock' not in _args else _args['lock']
  414. self.table = _args['table'] if 'table' in _args else None
  415. self.mode = {'if_exists':'append','chunksize':900000,'destination_table':self.table,'credentials':self.credentials}
  416. self._chunks = 1 if 'chunks' not in _args else int(_args['chunks'])
  417. def write(self,_info,**_args) :
  418. try:
  419. if self.parallel or 'lock' in _args :
  420. BQWriter.lock.acquire()
  421. _args['table'] = self.table if 'table' not in _args else _args['table']
  422. self._write(_info,**_args)
  423. finally:
  424. if self.parallel:
  425. BQWriter.lock.release()
  426. def _write(self,_info,**_args) :
  427. _df = None
  428. if type(_info) in [list,pd.DataFrame] :
  429. if type(_info) == list :
  430. _df = pd.DataFrame(_info)
  431. elif type(_info) == pd.DataFrame :
  432. _df = _info
  433. if '.' not in _args['table'] :
  434. self.mode['destination_table'] = '.'.join([self.dataset,_args['table']])
  435. else:
  436. self.mode['destination_table'] = _args['table'].strip()
  437. if 'schema' in _args :
  438. self.mode['table_schema'] = _args['schema']
  439. #
  440. # Let us insure that the types are somewhat compatible ...
  441. # _map = {'INTEGER':np.int64,'DATETIME':'datetime64[ns]','TIMESTAMP':'datetime64[ns]','FLOAT':np.float64,'DOUBLE':np.float64,'STRING':str}
  442. # _mode = copy.deepcopy(self.mode)
  443. _mode = self.mode
  444. # _df.to_gbq(**self.mode) #if_exists='append',destination_table=partial,credentials=credentials,chunksize=90000)
  445. #
  446. # Let us adjust the chunking here
  447. self._chunks = 10 if _df.shape[0] > SQLRW.MAX_CHUNK and self._chunks == 1 else self._chunks
  448. _indexes = np.array_split(np.arange(_df.shape[0]),self._chunks)
  449. for i in _indexes :
  450. _df.iloc[i].to_gbq(**self.mode)
  451. time.sleep(1)
  452. pass
  453. #
  454. # Aliasing the big query classes allowing it to be backward compatible
  455. #
  456. BigQueryReader = BQReader
  457. BigQueryWriter = BQWriter