Open rbroth opened 7 months ago
Hi @rbroth,
That would be a nice enhancement. I've have to do similar things in PostgreSQL before. We'd need to check the implementation for there, and what we need in SQLite (when you have multiple databases connected that act like schemas) and in MS SQL before we could add it.
In the meantime, the OracleDB docs suggest that the current_schema
attribute is read/write, so it should be possible to shorten your code by:
with ORACLEDB.connect(password_variable='DB_PASSWORD') as conn:
conn.current_schema = "dev_hr"
...
You can save setting it each time by defining a function to connect and update the schema in one step:
from contextlib import contextmanager
@contextmanager
def connect_to_schema(db_params, password_variable, schema):
try:
conn = db_params.connect(password_variable=password_variable)
conn.current_schema = schema
yield conn
finally:
conn.close()
# Example usage
with connect_to_schema(ORACLE_DB, "DB_PASSWORD", "dev_hr") as conn:
result = etl.fetchall("SELECT * FROM my_table", conn)
In oracle, when you write sql code targeting a db object without specifying it's schema, oracle assumes that is the same as the username e.g. if user
alice
connects to the db and executesSELECT * FROM mytable
, oracle will interpret it asSELECT * FROM alice.mytable
. If Alice wants her script to work with bothdev_hr
andprod_hr
, she either has to prefix all of her object names with a variable (leading to clunky code), or runevery time she opens up a db connection.
It is possible to set the default schema for a session, so that you can specify what schema gets set before an unqualified db object name (see e.g. https://python-oracledb.readthedocs.io/en/latest/api_manual/connection.html#Connection.current_schema).
It would be useful if we added an attribute for DBParams that would allow setting the default schema, e.g.: