sql.py 12 KB

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