sql.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. if sys.version_info[0] > 2 :
  13. from transport.common import Reader, Writer #, factory
  14. else:
  15. from common import Reader,Writer
  16. import json
  17. from google.oauth2 import service_account
  18. from google.cloud import bigquery as bq
  19. from multiprocessing import Lock
  20. import pandas as pd
  21. import numpy as np
  22. import nzpy as nz #--- netezza drivers
  23. import copy
  24. class SQLRW :
  25. PROVIDERS = {"postgresql":"5432","redshift":"5432","mysql":"3306","mariadb":"3306","netezza":5480}
  26. DRIVERS = {"postgresql":pg,"redshift":pg,"mysql":my,"mariadb":my,"netezza":nz}
  27. REFERENCE = {
  28. "netezza":{"port":5480,"handler":nz,"dtype":"VARCHAR(512)"},
  29. "postgresql":{"port":5432,"handler":pg,"dtype":"VARCHAR"},
  30. "redshift":{"port":5432,"handler":pg,"dtype":"VARCHAR"},
  31. "mysql":{"port":3360,"handler":my,"dtype":"VARCHAR(256)"},
  32. "mariadb":{"port":3360,"handler":my,"dtype":"VARCHAR(256)"},
  33. }
  34. def __init__(self,**_args):
  35. _info = {}
  36. _info['dbname'] = _args['db'] if 'db' in _args else _args['database']
  37. self.table = _args['table']
  38. self.fields = _args['fields'] if 'fields' in _args else []
  39. _provider = _args['provider']
  40. if 'host' in _args :
  41. _info['host'] = 'localhost' if 'host' not in _args else _args['host']
  42. # _info['port'] = SQLWriter.PROVIDERS[_args['provider']] if 'port' not in _args else _args['port']
  43. _info['port'] = SQLWriter.REFERENCE[_provider]['port'] if 'port' not in _args else _args['port']
  44. if 'username' in _args or 'user' in _args:
  45. key = 'username' if 'username' in _args else 'user'
  46. _info['user'] = _args[key]
  47. _info['password'] = _args['password']
  48. #
  49. # We need to load the drivers here to see what we are dealing with ...
  50. # _handler = SQLWriter.DRIVERS[_args['provider']]
  51. _handler = SQLWriter.REFERENCE[_provider]['handler']
  52. self._dtype = SQLWriter.REFERENCE[_provider]['dtype'] if 'dtype' not in _args else _args['dtype']
  53. self._provider = _provider
  54. if _handler == nz :
  55. _info['database'] = _info['dbname']
  56. _info['securityLevel'] = 0
  57. del _info['dbname']
  58. self.conn = _handler.connect(**_info)
  59. def isready(self):
  60. _sql = "SELECT * FROM :table LIMIT 1".replace(":table",self.table)
  61. try:
  62. return pd.read_sql(_sql,self.conn).columns.tolist()
  63. except Exception as e:
  64. pass
  65. return False
  66. def apply(self,_sql):
  67. """
  68. This function applies a command and/or a query against the current relational data-store
  69. :param _sql insert/select statement
  70. @TODO: Store procedure calls
  71. """
  72. cursor = self.conn.cursor()
  73. _out = None
  74. try:
  75. if "select" in _sql.lower() :
  76. cursor.close()
  77. return pd.read_sql(_sql,self.conn)
  78. else:
  79. # Executing a command i.e no expected return values ...
  80. cursor.execute(_sql)
  81. self.conn.commit()
  82. except Exception as e :
  83. print (e)
  84. finally:
  85. self.conn.commit()
  86. cursor.close()
  87. def close(self):
  88. try:
  89. self.conn.close()
  90. except Exception as error :
  91. print (error)
  92. pass
  93. class SQLReader(SQLRW,Reader) :
  94. def __init__(self,**_args):
  95. super().__init__(**_args)
  96. def read(self,**_args):
  97. if 'sql' in _args :
  98. _sql = (_args['sql'])
  99. else:
  100. _sql = "SELECT :fields FROM "+self.table
  101. if 'filter' in _args :
  102. _sql = _sql +" WHERE "+_args['filter']
  103. _fields = '*' if not self.fields else ",".join(self.fields)
  104. _sql = _sql.replace(":fields",_fields)
  105. if 'limit' in _args :
  106. _sql = _sql + " LIMIT "+str(_args['limit'])
  107. return self.apply(_sql)
  108. def close(self) :
  109. try:
  110. self.conn.close()
  111. except Exception as error :
  112. print (error)
  113. pass
  114. class SQLWriter(SQLRW,Writer):
  115. def __init__(self,**_args) :
  116. super().__init__(**_args)
  117. #
  118. # In the advent that data typing is difficult to determine we can inspect and perform a default case
  119. # This slows down the process but improves reliability of the data
  120. # NOTE: Proper data type should be set on the target system if their source is unclear.
  121. self._inspect = False if 'inspect' not in _args else _args['inspect']
  122. self._cast = False if 'cast' not in _args else _args['cast']
  123. def init(self,fields=None):
  124. if not fields :
  125. try:
  126. self.fields = pd.read_sql("SELECT * FROM :table LIMIT 1".replace(":table",self.table),self.conn).columns.tolist()
  127. finally:
  128. pass
  129. else:
  130. self.fields = fields;
  131. def make(self,fields):
  132. self.fields = fields
  133. sql = " ".join(["CREATE TABLE",self.table," (", ",".join([ name +' '+ self._dtype for name in fields]),")"])
  134. cursor = self.conn.cursor()
  135. try:
  136. cursor.execute(sql)
  137. except Exception as e :
  138. print (e)
  139. pass
  140. finally:
  141. cursor.close()
  142. def write(self,info):
  143. """
  144. :param info writes a list of data to a given set of fields
  145. """
  146. # inspect = False if 'inspect' not in _args else _args['inspect']
  147. # cast = False if 'cast' not in _args else _args['cast']
  148. if not self.fields :
  149. if type(info) == list :
  150. _fields = info[0].keys()
  151. elif type(info) == dict :
  152. _fields = info.keys()
  153. elif type(info) == pd.DataFrame :
  154. _fields = info.columns
  155. # _fields = info.keys() if type(info) == dict else info[0].keys()
  156. _fields = list (_fields)
  157. self.init(_fields)
  158. #
  159. # @TODO: Use pandas/odbc ? Not sure b/c it requires sqlalchemy
  160. #
  161. if type(info) != list :
  162. #
  163. # We are assuming 2 cases i.e dict or pd.DataFrame
  164. info = [info] if type(info) == dict else info.values.tolist()
  165. cursor = self.conn.cursor()
  166. try:
  167. _sql = "INSERT INTO :table (:fields) VALUES (:values)".replace(":table",self.table) #.replace(":table",self.table).replace(":fields",_fields)
  168. if self._inspect :
  169. for _row in info :
  170. fields = list(_row.keys())
  171. if self._cast == False :
  172. values = ",".join(_row.values())
  173. else:
  174. # values = "'"+"','".join([str(value) for value in _row.values()])+"'"
  175. values = [",".join(["%(",name,")s"]) for name in _row.keys()]
  176. # values = [ "".join(["'",str(_row[key]),"'"]) if np.nan(_row[key]).isnumeric() else str(_row[key]) for key in _row]
  177. # print (values)
  178. query = _sql.replace(":fields",",".join(fields)).replace(":values",values)
  179. cursor.execute(query,_row.values())
  180. pass
  181. else:
  182. _fields = ",".join(self.fields)
  183. # _sql = _sql.replace(":fields",_fields)
  184. # _sql = _sql.replace(":values",",".join(["%("+name+")s" for name in self.fields]))
  185. _sql = _sql.replace("(:fields)","")
  186. values = ", ".join("?"*len(self.fields)) if self._provider == 'netezza' else ",".join(["%s" for name in self.fields])
  187. _sql = _sql.replace(":values",values)
  188. # for row in info :
  189. # values = ["'".join(["",value,""]) if not str(value).isnumeric() else value for value in row.values()]
  190. cursor.executemany(_sql,info)
  191. # self.conn.commit()
  192. except Exception as e:
  193. print(e)
  194. pass
  195. finally:
  196. self.conn.commit()
  197. cursor.close()
  198. pass
  199. def close(self):
  200. try:
  201. self.conn.close()
  202. finally:
  203. pass
  204. class BigQuery:
  205. def __init__(self,**_args):
  206. path = _args['service_key'] if 'service_key' in _args else _args['private_key']
  207. self.credentials = service_account.Credentials.from_service_account_file(path)
  208. self.dataset = _args['dataset'] if 'dataset' in _args else None
  209. self.path = path
  210. self.dtypes = _args['dtypes'] if 'dtypes' in _args else None
  211. def meta(self,**_args):
  212. """
  213. This function returns meta data for a given table or query with dataset/table properly formatted
  214. :param table name of the name WITHOUT including dataset
  215. :param sql sql query to be pulled,
  216. """
  217. #if 'table' in _args :
  218. # sql = "SELECT * from :dataset."+ _args['table']" limit 1"
  219. #else:
  220. # sql = _args['sql']
  221. # if 'limit' not in sql.lower() :
  222. # sql = sql + ' limit 1'
  223. #sql = sql.replace(':dataset',self.dataset) if ':dataset' in args else sql
  224. #
  225. # Let us return the schema information now for a given table
  226. #
  227. table = _args['table']
  228. client = bq.Client.from_service_account_json(self.path)
  229. ref = client.dataset(self.dataset).table(table)
  230. return client.get_table(ref).schema
  231. class BQReader(BigQuery,Reader) :
  232. def __init__(self,**_args):
  233. super().__init__(**_args)
  234. pass
  235. def read(self,**_args):
  236. SQL = None
  237. if 'sql' in _args :
  238. SQL = _args['sql']
  239. elif 'table' in _args:
  240. table = "".join(["`",_args['table'],"`"])
  241. SQL = "SELECT * FROM :table ".replace(":table",table)
  242. if SQL and 'limit' in _args:
  243. SQL += " LIMIT "+str(_args['limit'])
  244. if (':dataset' in SQL or ':DATASET' in SQL) and self.dataset:
  245. SQL = SQL.replace(':dataset',self.dataset).replace(':DATASET',self.dataset)
  246. _info = {'credentials':self.credentials,'dialect':'standard'}
  247. return pd.read_gbq(SQL,**_info) if SQL else None
  248. # return pd.read_gbq(SQL,credentials=self.credentials,dialect='standard') if SQL else None
  249. class BQWriter(BigQuery,Writer):
  250. lock = Lock()
  251. def __init__(self,**_args):
  252. super().__init__(**_args)
  253. self.parallel = False if 'lock' not in _args else _args['lock']
  254. self.table = _args['table'] if 'table' in _args else None
  255. self.mode = {'if_exists':'append','chunksize':900000,'destination_table':self.table,'credentials':self.credentials}
  256. def write(self,_info,**_args) :
  257. try:
  258. if self.parallel or 'lock' in _args :
  259. BQWriter.lock.acquire()
  260. self._write(_info,**_args)
  261. finally:
  262. if self.parallel:
  263. BQWriter.lock.release()
  264. def _write(self,_info,**_args) :
  265. _df = None
  266. if type(_info) in [list,pd.DataFrame] :
  267. if type(_info) == list :
  268. _df = pd.DataFrame(_info)
  269. elif type(_info) == pd.DataFrame :
  270. _df = _info
  271. if '.' not in _args['table'] :
  272. self.mode['destination_table'] = '.'.join([self.dataset,_args['table']])
  273. else:
  274. self.mode['destination_table'] = _args['table'].strip()
  275. if 'schema' in _args :
  276. self.mode['table_schema'] = _args['schema']
  277. # _mode = copy.deepcopy(self.mode)
  278. _mode = self.mode
  279. _df.to_gbq(**self.mode) #if_exists='append',destination_table=partial,credentials=credentials,chunksize=90000)
  280. pass