bricks.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """
  2. This file implements databricks handling, This functionality will rely on databricks-sql-connector
  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 os
  13. import sqlalchemy
  14. from transport.common import Reader,Writer
  15. import pandas as pd
  16. class Bricks:
  17. """
  18. :host
  19. :token
  20. :database
  21. :cluster_path
  22. :table
  23. """
  24. def __init__(self,**_args):
  25. _host = _args['host']
  26. _token= _args['token']
  27. _cluster_path = _args['cluster_path']
  28. self._schema = _args['schema'] if 'schema' in _args else _args['database']
  29. _catalog = _args['catalog']
  30. self._table = _args['table'] if 'table' in _args else None
  31. #
  32. # @TODO:
  33. # Sometimes when the cluster isn't up and running it takes a while, the user should be alerted of this
  34. #
  35. _uri = f'''databricks://token:{_token}@{_host}?http_path={_cluster_path}&catalog={_catalog}&schema={self._schema}'''
  36. self._engine = sqlalchemy.create_engine (_uri)
  37. pass
  38. def meta(self,**_args):
  39. table = _args['table'] if 'table' in _args else self._table
  40. if not table :
  41. return []
  42. else:
  43. if sqlalchemy.__version__.startswith('1.') :
  44. _m = sqlalchemy.MetaData(bind=self._engine)
  45. _m.reflect(only=[table])
  46. else:
  47. _m = sqlalchemy.MetaData()
  48. _m.reflect(bind=self._engine)
  49. #
  50. # Let's retrieve te information associated with a table
  51. #
  52. return [{'name':_attr.name,'type':_attr.type} for _attr in _m.tables[table].columns]
  53. def has(self,**_args):
  54. return self.meta(**_args)
  55. def apply(self,_sql):
  56. try:
  57. if _sql.lower().startswith('select') :
  58. return pd.read_sql(_sql,self._engine)
  59. except Exception as e:
  60. pass
  61. class BricksReader(Bricks,Reader):
  62. """
  63. This class is designed for reads and will execute reads against a table name or a select SQL statement
  64. """
  65. def __init__(self,**_args):
  66. super().__init__(**_args)
  67. def read(self,**_args):
  68. limit = None if 'limit' not in _args else str(_args['limit'])
  69. if 'sql' in _args :
  70. sql = _args['sql']
  71. elif 'table' in _args :
  72. table = _args['table']
  73. sql = f'SELECT * FROM {table}'
  74. if limit :
  75. sql = sql + f' LIMIT {limit}'
  76. if 'sql' in _args or 'table' in _args :
  77. return self.apply(sql)
  78. else:
  79. return pd.DataFrame()
  80. pass
  81. class BricksWriter(Bricks,Writer):
  82. def __init__(self,**_args):
  83. super().__init__(**_args)
  84. def write(self,_data,**_args):
  85. """
  86. This data will write data to data-bricks against a given table. If the table is not specified upon initiazation, it can be specified here
  87. _data: data frame to push to databricks
  88. _args: chunks, table, schema
  89. """
  90. _schema = self._schema if 'schema' not in _args else _args['schema']
  91. _table = self._table if 'table' not in _args else _args['table']
  92. _df = _data if type(_data) == pd.DataFrame else _data
  93. if type(_df) == dict :
  94. _df = [_df]
  95. if type(_df) == list :
  96. _df = pd.DataFrame(_df)
  97. _df.to_sql(
  98. name=_table,schema=_schema,
  99. con=self._engine,if_exists='append',index=False);
  100. pass