@ -1,11 +1,14 @@
"""
"""
This file encapsulates common operations associated with SQL databases via SQLAlchemy
This file encapsulates common operations associated with SQL databases via SQLAlchemy
@ENT :
- To support streaming ( with generators ) we the parameter chunksize which essentially enables streaming
"""
"""
import sqlalchemy as sqa
import sqlalchemy as sqa
from sqlalchemy import text , MetaData , inspect
from sqlalchemy import text , MetaData , inspect
import pandas as pd
import pandas as pd
def template ( ) :
return { ' host ' : ' localhost ' , ' database ' : ' database ' , ' table ' : ' table ' }
class Base :
class Base :
def __init__ ( self , * * _args ) :
def __init__ ( self , * * _args ) :
@ -20,6 +23,7 @@ class Base:
_uri , _kwargs = _uri
_uri , _kwargs = _uri
self . _engine = sqa . create_engine ( _uri , * * _kwargs , future = True )
self . _engine = sqa . create_engine ( _uri , * * _kwargs , future = True )
self . _chunksize = int ( _args [ ' chunksize ' ] ) if ' chunksize ' in _args else None
def _set_uri ( self , * * _args ) :
def _set_uri ( self , * * _args ) :
"""
"""
: provider provider
: provider provider
@ -78,7 +82,12 @@ class Base:
@TODO : Execution of stored procedures
@TODO : Execution of stored procedures
"""
"""
if sql . strip ( ) . lower ( ) . startswith ( ' select ' ) or sql . strip ( ) . lower ( ) . startswith ( ' with ' ) or sql . strip ( ) . startswith ( ' show ' ) :
if sql . strip ( ) . lower ( ) . startswith ( ' select ' ) or sql . strip ( ) . lower ( ) . startswith ( ' with ' ) or sql . strip ( ) . startswith ( ' show ' ) :
return pd . read_sql ( sql , self . _engine )
if not self . _chunksize :
return pd . read_sql ( sql , self . _engine )
else :
return pd . read_sql ( sql , self . _engine , chunksize = self . _chunksize )
else :
else :
_handler = self . _engine . connect ( )
_handler = self . _engine . connect ( )
_handler . execute ( text ( sql . strip ( ) ) )
_handler . execute ( text ( sql . strip ( ) ) )
@ -132,7 +141,12 @@ class BaseReader(SQLBase):
if self . _schema and type ( self . _schema ) == str :
if self . _schema and type ( self . _schema ) == str :
_table = f ' { self . _schema } . { _table } '
_table = f ' { self . _schema } . { _table } '
sql = f ' SELECT * FROM { _table } '
sql = f ' SELECT * FROM { _table } '
if ' chunksize ' in _args :
self . _chunksize = int ( _args [ ' chunksize ' ] )
return self . apply ( sql )
return self . apply ( sql )
class BaseWriter ( SQLBase ) :
class BaseWriter ( SQLBase ) :