tdfs4ds.utils.query_management¶
tdfs4ds.utils.query_management
¶
_DRIVER_FRAME_RE
module-attribute
¶
_SQLALCHEMY_BACKGROUND_RE
module-attribute
¶
DBC_FULL_WHY
module-attribute
¶
DBC_FULL_WHY = 'Database DBC, the data dictionary, has no room left. Every DDL statement and every write to the catalogs (registration, documentation, lineage, follow-up) needs room in it, so the same fault shows in calls unrelated to its cause. The usual culprits are the query-log tables (DBC.DBQLogTbl, DBC.DBQLExplainTbl and others) and a large DBC.TransientJournal, which an open transaction keeps growing.'
DBC_FULL_FIX
module-attribute
¶
DBC_FULL_FIX = 'Only an administrator can fix it: purge the query-log tables, end the transaction holding the transient journal (ABORT SESSION), or give DBC more space. Nothing tdfs4ds can do from here frees it.'
DBC_FULL_MEASURE
module-attribute
¶
DBC_FULL_MEASURE = "tdfs4ds.assess_workflow(checks=('dbc_space',)) reads the space of DBC (tdfs4ds.sanity_check() runs it with the other cheap checks)."
DBC_FULL_EXPLANATION
module-attribute
¶
_DBC_FULL_RE
module-attribute
¶
_ACCESS_RE
module-attribute
¶
_ACCESS_RE = re.compile('does not have\\s+(.+?)\\s+access to\\s+(\\S+?)\\.?(?:\\s|$)', re.IGNORECASE)
_METADATA_RE
module-attribute
¶
_METADATA_RE = _re.compile('^\\s*(HELP\\s|SHOW\\s|SELECT\\b[^;]*\\b(DBC\\.|ALL_RI_|SYSLIB\\.|DBC\\b))|\\bDBC\\.\\w+|\\bALL_RI_\\w+|\\bINDICESV\\b|\\bTABLESV\\b|\\bCOLUMNSV\\b', _re.IGNORECASE)
_DDL_RE
module-attribute
¶
_DDL_RE = _re.compile('^\\s*(CREATE|REPLACE|DROP|ALTER|RENAME|COMMENT|COLLECT\\s+STAT\\w*|DROP\\s+STAT\\w*)\\b', _re.IGNORECASE)
_DML_RE
module-attribute
¶
_DML_RE = _re.compile('^\\s*(?:\\w[\\w\\s]*?\\s)?(INSERT|UPDATE|DELETE|MERGE)\\b|^\\s*(INSERT|UPDATE|DELETE|MERGE)\\b', _re.IGNORECASE)
_SELECT_RE
module-attribute
¶
_SELECT_RE = _re.compile('^\\s*(\\(|WITH\\b|SEL\\b|SELECT\\b|EXPLAIN\\b|(CURRENT|NONSEQUENCED|SEQUENCED)\\s+VALIDTIME\\s+SEL)', _re.IGNORECASE)
DictionarySpaceError
¶
Bases: RuntimeError
Database DBC is full (Error 2644). The message explains the cause and who can fix it; the
driver exception is kept as __cause__.
StatementCount
¶
What :func:count_statements yields: total, by_kind, statements (the first
keep texts, truncated), enabled (False when no connection could be watched).
With timings=True (profiling, 0.3.7.20): seconds (time spent in statements),
timed ([(seconds, kind, text, caller)], every statement, full text), pandas
([(what, rows, seconds, caller)]: each DataFrame.to_pandas / copy_to_sql) and
stages ([(name, wall seconds, statement seconds, statements)] from :meth:stage).
The time of execute_sql is the time to send the statement and get its first answer;
fetching rows afterwards is not in it.
logger_safe
¶
Wrapper around the global logger that only emits logs when
tdfs4ds.DISPLAY_LOGS is True. level is a string like "info", "error", etc.
is_version_greater_than
¶
Check if the tested version is greater than the base version.
This function compares two version numbers, the 'tested_version' and the 'base_version',
to determine if the 'tested_version' is greater. It uses Python's version.parse function
to perform the comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tested_version
|
str
|
Version number to be tested. |
required |
base_version
|
str
|
Base version number to compare. Defaults to "17.20.00.03". |
'17.20.00.03'
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the 'tested_version' is greater than the 'base_version', False otherwise. |
Example
To check if a version is greater than the default base version:
is_greater = is_version_greater_than("17.20.00.04")
To check if a version is greater than a custom base version:
is_greater = is_version_greater_than("18.10.00.01", base_version="18.00.00.00")
execute_query_wrapper
¶
Decorator to execute a query. It wraps around the function and adds exception handling.
This decorator is used to wrap around a function that generates a query and execute that query.
It handles exceptions during query execution and prints the error message along with the query.
The decorator works with both TeradataML's tdml and legacy tdml.get_context() execution methods,
depending on the TeradataML version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
function
|
Function to be decorated. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
function |
Decorated function. |
Example
To decorate a function that generates and executes a query:
@execute_query_wrapper def my_query_function(): return "SELECT * FROM my_table"
This decorator can be applied to functions that generate and execute queries with ease.
describe_db_error
¶
The error message without the driver's stack trace.
Keeps EVERY message line — the half that names the fault is often not the first line — and drops only the Go frames teradatasql appends and the SQLAlchemy "Background on this error" link. Falls back to the raw text when nothing would be left.
is_dbc_full_error
¶
True when exc (or a cause of it) is the database's refusal for lack of room in database DBC.
Teradata words it "No more room in database DBC." (Error 2644). The phrase is matched, never the number, and the database named must be DBC: the same error on a user database is that user's space, not the dictionary.
dictionary_space_error
¶
The explained error for a DBC-full failure exc, with exc as its __cause__.
failure_status
¶
The text a failed run records after FAILED,: the first line of the error, and for a full
DBC the readable message instead of the bare driver line (the follow-up table is where people look).
explains_dictionary_space
¶
Decorator for the user-facing entry points: a DBC-full failure leaves as a
:class:DictionarySpaceError (the explanation, the driver exception as __cause__); every other
exception passes through untouched. Nothing is swallowed.
execute_query
¶
Execute a SQL query or a list of queries using the tdml module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str or list
|
A single SQL query string or a list of SQL query strings. |
required |
raise_error
|
bool
|
If True, re-raise exceptions after printing them. Default is False. |
False
|
fetch_results
|
bool
|
If True, fetch and return the results of the SQL execution. Default is False. |
False
|
quiet_errors
|
tuple
|
Lowercase substrings identifying failures the caller
EXPECTS and will handle itself. A matching failure is logged at DEBUG
instead of ERROR; whether it is re-raised is still governed by
|
()
|
log_errors
|
bool
|
False when the caller re-raises ( |
True
|
Returns: The result of the SQL execution if a single query is passed. None if a list of queries is passed or an exception occurs.
is_already_exists_error
¶
True when a failed CREATE means the object was already there.
The single authority for that question. It is deliberately NOT "this is an error we tolerate" — for an idempotent CREATE, an object that already exists is the nominal outcome, and reporting it as an error is what makes logs unusable for supervision.
is_access_denied_error
¶
True when the database refused the statement for lack of a right.
Teradata words every such refusal "The user does not have
access_refusal
¶
(right, object) named by an access refusal, else None.
"The user does not have SELECT access to DB.T.C." -> ('SELECT', 'DB.T.C').
The object is what Teradata names: the table, view or column it refused.
grant_hint
¶
The GRANT that would lift exc's refusal, as advice (never executed).
create_object_if_missing
¶
Run an idempotent CREATE and report honestly what happened.
This exists because of a structural trap: execute_query defaults to
raise_error=False, so it logs the failure itself and returns normally —
an except wrapped around it never sees anything. Every catalog-creation
block written that way therefore logged an ERROR for a store that was simply
already provisioned, then went on to log "has been created" for a table it
had not created, while its own already-exists handling sat unreachable.
Parameters¶
create_query : str
The CREATE statement.
label : str
Human-readable object name for the log lines (e.g. "TABLE DB.FS_X").
follow_up : iterable of str
Statements to run once the object is known to be present, whether this
call created it or found it. They must be idempotent — COMMENT ON
and REPLACE VIEW are the intended uses.
Returns¶
bool True if this call created the object, False if it was already there.
Raises¶
Exception The original driver exception for any failure that is NOT "already exists" — logged at ERROR with the full message, because the half that names the fault is often the later half.
db_object_names
¶
Names of the objects teradataml.db_list_tables lists in schema_name, as given.
An empty database lists a frame with no TableName column at all (seen live: setup(if_exists=
'replace') on a new database died on .TableName), so read the column only when it is there.
classify_statement
¶
metadata (HELP / SHOW / DBC views / referential-integrity views, what a DataFrame
construction issues), ddl, dml, select or other.
_caller_in_package
¶
module:line function of the innermost tdfs4ds frame outside this module (profiling).
_watched_engine
¶
The SQLAlchemy engine of teradataml's current context (either layout), else None.
count_statements
¶
Count the statements sent to Teradata inside the with block.
Two paths are watched, and none is counted twice: what teradataml sends through its SQLAlchemy
engine (DataFrame construction and its metadata reflection) via a before_cursor_execute
listener, and teradataml.execute_sql (which uses the raw driver connection, so no engine
event fires for it). Statements sent by other raw teradatasql connections are not seen.
Fail-open: with no engine to watch, a warning is logged once and nothing is counted.
with tdfs4ds.count_statements() as n: ... tdfs4ds.roll_out(...) n.total, n.by_kind, n.per(processes=4, dates=7)