sql.py 19 KB

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