locopy.database module¶
Database Module.
- class locopy.database.Database(dbapi, config_yaml=None, **kwargs)[source]¶
Bases:
object
Base class for all DBAPI 2 database connectors which will inherit this functionality.
The
Database
class will manage connections and handle executing queries. Most of the functionality should work out of the box for classes which inherit minus the abstract method forconnect
which may vary across databases.- Parameters:
dbapi (DBAPI 2 module, optional) – A database adapter which is Python DB API 2.0 compliant (
psycopg2
,pg8000
, etc.)config_yaml (str, optional) – String representing the YAML file location of the database connection keyword arguments. It is worth noting that this should only contain valid arguments for the database connector you plan on using. It will throw an exception if something is passed through which isn’t valid.
**kwargs – Database connection keyword arguments.
- dbapi¶
database adapter which is Python DBAPI 2.0 compliant
- Type:
DBAPI 2 module
- conn¶
DBAPI connection instance
- Type:
dbapi.connection
- cursor¶
DBAPI cursor instance
- Type:
dbapi.cursor
- Raises:
CredentialsError – Database credentials are not provided, valid, or both kwargs and a YAML config was provided.
- column_names()[source]¶
Pull column names out of the cursor description.
Depending on the DBAPI, it could return column names as bytes:
b'column_name'
.- Returns:
List of column names, all in lower-case
- Return type:
- connect()[source]¶
Create a connection to a database.
Sets the values of the
conn
andcursor
attributes.- Raises:
DBError – If there is a problem establishing a connection.
- disconnect()[source]¶
Terminate the connection.
Closes the values of the
conn
andcursor
attributes.- Raises:
DBError – If there is a problem disconnecting from the database.
- execute(sql, commit=True, params=(), many=False, verbose=True)[source]¶
Execute some sql against the connection.
- Parameters:
sql (str) – SQL to run against the connection. Could be one or multiple statements.
commit (Boolean, default True) – Whether to “commit” the commands to the cluster immediately or not.
params (iterable of parameters) – Parameters to submit with the query. The exact syntax will depend on the database adapter you are using
many (bool, default False) – Whether to execute the script as an “execute many”
verbose (bool, default True) – Whether to print executed query
- Raises:
- to_dataframe(df_type='pandas', size=None)[source]¶
Return a dataframe of the last query results.
- Parameters:
df_type (Literal["pandas","polars"], optional) – Output dataframe format. Defaults to pandas.
size (int, optional) – Chunk size to fetch. Defaults to None.
- Returns:
Dataframe with lowercase column names. Returns None if no fetched result.
- Return type:
pandas.DataFrame or polars.DataFrame