sql.py 17 KB

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