sql.py 21 KB

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