From 0da32069e2ca5245b13d9a70159c95f0dfd53774 Mon Sep 17 00:00:00 2001 From: Steve Nyemba Date: Fri, 8 Sep 2023 11:28:35 -0500 Subject: [PATCH] databricks support --- transport/__init__.py | 15 +++++- transport/bricks.py | 111 +++++++++++++++++++++++++++++++++++++++++ transport/providers.py | 11 ++-- transport/sql.py | 4 +- transport/version.py | 2 +- 5 files changed, 135 insertions(+), 8 deletions(-) create mode 100644 transport/bricks.py diff --git a/transport/__init__.py b/transport/__init__.py index 8a45800..4c2270c 100644 --- a/transport/__init__.py +++ b/transport/__init__.py @@ -157,20 +157,33 @@ class factory : return anObject import time -def instance(**_args): +def instance(**_pargs): """ creating an instance given the provider, we should have an idea of :class, :driver :provider :read|write = {connection to the database} """ + # + # @TODO: provide authentication file that will hold all the parameters, that will later on be used + # + _args = dict(_pargs,**{}) + if 'auth_file' in _args : + path = _args['auth_file'] + file = open(path) + _config = json.loads( file.read()) + _args = dict(_args,**_config) + file.close() + _provider = _args['provider'] _group = None + for _id in providers.CATEGORIES : if _provider in providers.CATEGORIES[_id] : _group = _id break if _group : + _classPointer = _getClassInstance(_group,**_args) # # Let us reformat the arguments diff --git a/transport/bricks.py b/transport/bricks.py new file mode 100644 index 0000000..0aa4383 --- /dev/null +++ b/transport/bricks.py @@ -0,0 +1,111 @@ +""" +This file implements databricks handling, This functionality will rely on databricks-sql-connector +LICENSE (MIT) +Copyright 2016-2020, The Phi Technology LLC + +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: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +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. + + +@TODO: + - Migrate SQLite to SQL hierarchy + - Include Write in Chunks from pandas +""" +import os +import sqlalchemy +from transport.common import Reader,Writer +import pandas as pd + + +class Bricks: + """ + :host + :token + :database + :cluster_path + :table + """ + def __init__(self,**_args): + _host = _args['host'] + _token= _args['token'] + _cluster_path = _args['cluster_path'] + self._schema = _args['schema'] if 'schema' in _args else _args['database'] + _catalog = _args['catalog'] + self._table = _args['table'] if 'table' in _args else None + + # + # @TODO: + # Sometimes when the cluster isn't up and running it takes a while, the user should be alerted of this + # + + _uri = f'''databricks://token:{_token}@{_host}?http_path={_cluster_path}&catalog={_catalog}&schema={self._schema}''' + self._engine = sqlalchemy.create_engine (_uri) + pass + def meta(self,**_args): + table = _args['table'] if 'table' in _args else self._table + if not table : + return [] + else: + if sqlalchemy.__version__.startswith('1.') : + _m = sqlalchemy.MetaData(bind=self._engine) + _m.reflect(only=[table]) + else: + _m = sqlalchemy.MetaData() + _m.reflect(bind=self._engine) + # + # Let's retrieve te information associated with a table + # + return [{'name':_attr.name,'type':_attr.type} for _attr in _m.tables[table].columns] + + def has(self,**_args): + return self.meta(**_args) + def apply(self,_sql): + try: + if _sql.lower().startswith('select') : + return pd.read_sql(_sql,self._engine) + except Exception as e: + pass + +class BricksReader(Bricks,Reader): + """ + This class is designed for reads and will execute reads against a table name or a select SQL statement + """ + def __init__(self,**_args): + super().__init__(**_args) + def read(self,**_args): + limit = None if 'limit' not in _args else str(_args['limit']) + + if 'sql' in _args : + sql = _args['sql'] + elif 'table' in _args : + table = _args['table'] + sql = f'SELECT * FROM {table}' + if limit : + sql = sql + f' LIMIT {limit}' + + if 'sql' in _args or 'table' in _args : + return self.apply(sql) + else: + return pd.DataFrame() + pass +class BricksWriter(Bricks,Writer): + def __init__(self,**_args): + super().__init__(**_args) + def write(self,_data,**_args): + """ + 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 + _data: data frame to push to databricks + _args: chunks, table, schema + """ + _schema = self._schema if 'schema' not in _args else _args['schema'] + _table = self._table if 'table' not in _args else _args['table'] + _df = _data if type(_data) == pd.DataFrame else _data + if type(_df) == dict : + _df = [_df] + if type(_df) == list : + _df = pd.DataFrame(_df) + _df.to_sql( + name=_table,schema=_schema, + con=self._engine,if_exists='append',index=False); + pass diff --git a/transport/providers.py b/transport/providers.py index 4fe4784..a638a89 100644 --- a/transport/providers.py +++ b/transport/providers.py @@ -8,6 +8,7 @@ from transport import mongo as mongo from transport import sql as sql from transport import etl as etl from transport import qlistener +from transport import bricks import psycopg2 as pg import mysql.connector as my from google.cloud import bigquery as bq @@ -45,16 +46,18 @@ AWS_S3 = 's3' RABBIT = RABBITMQ QLISTENER = 'qlistener' - +DATABRICKS= 'databricks+connector' DRIVERS = {PG:pg,REDSHIFT:pg,MYSQL:my,MARIADB:my,NETEZZA:nz,SQLITE:sqlite3} -CATEGORIES ={'sql':[NETEZZA,PG,MYSQL,REDSHIFT,SQLITE,MARIADB],'nosql':[MONGODB,COUCHDB],'cloud':[BIGQUERY],'file':[FILE], +CATEGORIES ={'sql':[NETEZZA,PG,MYSQL,REDSHIFT,SQLITE,MARIADB],'nosql':[MONGODB,COUCHDB],'cloud':[BIGQUERY,DATABRICKS],'file':[FILE], 'queue':[RABBIT,QLISTENER],'memory':[CONSOLE,QLISTENER],'http':[HTTP]} -READ = {'sql':sql.SQLReader,'nosql':{MONGODB:mongo.MongoReader,COUCHDB:couch.CouchReader},'cloud':sql.BigQueryReader, +READ = {'sql':sql.SQLReader,'nosql':{MONGODB:mongo.MongoReader,COUCHDB:couch.CouchReader}, + 'cloud':{BIGQUERY:sql.BigQueryReader,DATABRICKS:bricks.BricksReader}, 'file':disk.DiskReader,'queue':{RABBIT:queue.QueueReader,QLISTENER:qlistener.qListener}, 'cli':{CONSOLE:Console},'memory':{CONSOLE:Console} } -WRITE = {'sql':sql.SQLWriter,'nosql':{MONGODB:mongo.MongoWriter,COUCHDB:couch.CouchWriter},'cloud':sql.BigQueryWriter, +WRITE = {'sql':sql.SQLWriter,'nosql':{MONGODB:mongo.MongoWriter,COUCHDB:couch.CouchWriter}, + 'cloud':{BIGQUERY:sql.BigQueryWriter,DATABRICKS:bricks.BricksWriter}, 'file':disk.DiskWriter,'queue':{RABBIT:queue.QueueWriter,QLISTENER:qlistener.qListener},'cli':{CONSOLE:Console},'memory':{CONSOLE:Console} } diff --git a/transport/sql.py b/transport/sql.py index da412fa..3c555f5 100644 --- a/transport/sql.py +++ b/transport/sql.py @@ -431,8 +431,8 @@ class BQReader(BigQuery,Reader) : super().__init__(**_args) def apply(self,sql): - self.read(sql=sql) - pass + return self.read(sql=sql) + def read(self,**_args): SQL = None table = self.table if 'table' not in _args else _args['table'] diff --git a/transport/version.py b/transport/version.py index 9db71e5..6d0f952 100644 --- a/transport/version.py +++ b/transport/version.py @@ -1,2 +1,2 @@ __author__ = 'The Phi Technology' -__version__= '1.8.2' +__version__= '1.8.4'