Skip to content

tdfs4ds.impact_measure

tdfs4ds.impact_measure

Measure the proposed SQL against the current one, on volatile tables, on demand only.

:func:measure computes the current SELECT and the proposed SELECT into two VOLATILE tables of ONE raw teradatasql session (TDFS_IMPACT_OLD and TDFS_IMPACT_NEW), times each, reads their row counts and columns, compares them on the entity key (column by column, NULL-safe) and drops them.

  • Both SELECTs are computed in full: there is no row limit and no SAMPLE (a Teradata sample is random, so two samples cannot be compared row by row). A process view is already scoped by its managers (the TimeManager / FilterManager scalars), so its full result is one run's worth of rows.
  • A volatile table lives in its session only: nothing is stored, no catalog, follow-up or permanent object is touched, and every statement runs on the same connection (another session cannot see the tables). teradataml's shared context is never used.
  • A leading locking modifier (LOCKING ROW FOR ACCESS, LOCKING TABLE t FOR ACCESS, LOCK ...) and the comments are dropped from the SELECT of the temporary copy: CREATE VOLATILE TABLE ... AS (LOCKING ... SELECT ...) is Error 3707, and the copy only reads.
  • It is gated first by the EXPLAIN estimate of both SELECTs. The limits are SAMPLE_MAX_SECONDS / SAMPLE_MAX_SPOOL_GB (as the samples of the app), raised to :data:tdfs4ds.impact_reference.REFERENCE_FACTOR times the process's logged median run when that is higher (reference, :func:tdfs4ds.impact_reference.effective_limits). An estimate above the limits is refused unless force; a low-confidence estimate is refused too when its plan shows a product join or a spool over the limit, and only warned about otherwise.
  • It is cancellable (cancel_event: conn.cancel() stops the running statement in the database) and stopped after SAMPLE_JOB_MAX_SECONDS.
  • The tables are dropped in a finally and a last HELP VOLATILE TABLE proves they are gone.
  • The measuring session carries a query band TDFS_IMPACT=<id> (set on that connection only), so the CPU and I/O of its two CREATEs can be read from DBQL later with :func:read_resources: DBQL writes its rows from a cache (10 minutes by default), so they are usually not there when the study ends.

ALLOW-LIST. Every statement is checked before it is sent: SELECT, EXPLAIN, HELP VOLATILE TABLE, SET QUERY_BAND = 'TDFS_IMPACT=<32 hex>;' FOR SESSION, CREATE VOLATILE TABLE TDFS_IMPACT_OLD|NEW AS (<select>) WITH DATA ON COMMIT PRESERVE ROWS and DROP TABLE TDFS_IMPACT_OLD|NEW. Anything else raises before it reaches the database.

Not part of this allow-list: the EXPLAIN comparison of the study (:mod:tdfs4ds.impact_efficiency) runs its DYNAMIC EXPLAIN under :func:tdfs4ds.utils.query_band.forced_incremental_planning, which sets a session query band on teradataml's connection and restores it afterwards.

TABLES module-attribute

TABLES = (OLD_TABLE, NEW_TABLE)

COLUMNS_PER_STATEMENT module-attribute

COLUMNS_PER_STATEMENT = 100

MAX_EXAMPLE_COLUMNS module-attribute

MAX_EXAMPLE_COLUMNS = 20

EXAMPLES module-attribute

EXAMPLES = 3

TAG_NAME module-attribute

TAG_NAME = 'TDFS_IMPACT'

DBQL_LAG module-attribute

DBQL_LAG = 'DBQL rows are written from a cache (10 minutes by default): the CPU and I/O of a statement that just ended are often not there yet; refresh the resource figures later'

LOCKING_NOTE module-attribute

LOCKING_NOTE = 'locking modifier dropped for the temporary copy (reads only)'

_IDENT module-attribute

_IDENT = re.compile('^[A-Za-z_][\\w$#]*$')

_CTAS module-attribute

_CTAS = re.compile('^CREATE VOLATILE TABLE (TDFS_IMPACT_OLD|TDFS_IMPACT_NEW) AS \\(.+\\) WITH DATA ON COMMIT PRESERVE ROWS$', re.S)

_DROP module-attribute

_DROP = re.compile('^DROP TABLE (TDFS_IMPACT_OLD|TDFS_IMPACT_NEW)$')

_BAND module-attribute

_BAND = re.compile("^SET QUERY_BAND = 'TDFS_IMPACT=[0-9a-f]{32};' FOR SESSION$")

_TAG module-attribute

_TAG = re.compile('^[0-9a-f]{32}$')

_READS module-attribute

_READS = ('SELECT ', 'SEL ', 'EXPLAIN ', 'HELP VOLATILE TABLE')

DEFAULTS module-attribute

DEFAULTS = {'SAMPLE_MAX_SECONDS': 60, 'SAMPLE_MAX_SPOOL_GB': 10, 'SAMPLE_JOB_MAX_SECONDS': 600}

_LOCKING module-attribute

_LOCKING = re.compile('^\\s*LOCK(?:ING)?\\s+(?:(?:ROW|TABLE|DATABASE|VIEW)\\s+)?(?:(?!(?:FOR|IN)\\b)(?:\\"[^\\"]*\\"|[\\w$#]+)(?:\\s*\\.\\s*(?:\\"[^\\"]*\\"|[\\w$#]+))?\\s+)?(?:(?:FOR|IN)\\s+)?(?:ACCESS|READ|SHARE|WRITE|EXCLUSIVE|LOAD|CHECKSUM)\\b(?:\\s+MODE\\b)?(?:\\s+NOWAIT\\b)?\\s*', re.IGNORECASE)

StatementRefused

Bases: ValueError

A statement outside the allow-list was about to be sent.

_Cancelled

Bases: Exception

_Refused

Bases: Exception

check_statement

check_statement(sql: str) -> str

Return sql when the allow-list accepts it; raise :class:StatementRefused otherwise. Pure.

_err

_err(exc) -> str

_q

_q(name: str) -> str

_setting

_setting(name, default) -> float

remove_comments

remove_comments(sql: str) -> str

sql with its -- and /* */ comments replaced by a space; string literals and quoted names are kept as they are. Pure.

ctas_select

ctas_select(select: str) -> Tuple[str, bool]

(select, dropped): the SELECT a volatile copy can hold. Comments and a trailing ; are removed, and every leading locking modifier (LOCKING ROW FOR ACCESS, LOCKING TABLE t FOR READ, LOCK ROW FOR ACCESS, ...) is dropped (dropped = True): CREATE VOLATILE TABLE ... AS (LOCKING ... SELECT ...) is Error 3707. Anything else is kept as it is; a SELECT that only contains the word LOCKING is untouched. Pure.

ctas_sql

ctas_sql(table: str, select: str) -> str

The CREATE VOLATILE TABLE of one side, from :func:ctas_select. Pure.

drop_sql

drop_sql(table: str) -> str

band_sql

band_sql(tag: str) -> str

The query band that tags the measuring session (its own connection only). Pure.

_differs

_differs(col: str) -> str

_null_change

_null_change(col: str) -> str

_join

_join(entity_columns: List[str]) -> str

compare_sql

compare_sql(entity_columns: List[str], columns: List[str]) -> str

One statement: compared rows, then per column the rows that differ and the NULL changes.

examples_sql

examples_sql(entity_columns: List[str], col: str, n: int = EXAMPLES) -> str

only_in_sql

only_in_sql(first: str, other: str, entity_columns: List[str]) -> str

duplicate_keys_sql

duplicate_keys_sql(table: str, entity_columns: List[str]) -> str

resources_sql

resources_sql(session=None, tag: Optional[str] = None) -> str

The DBQL rows of the two CREATEs of a measurement, by its query band tag (preferred) or its session number. Pure.

gate

gate(costs: Dict[str, dict], max_spool_bytes: float, force: bool = False) -> dict

{refuse, over, notes} from the :func:tdfs4ds.utils.explain_cost.assess_explain of each side.

A side above the limits is refused unless force. Low confidence only waives the refusal for a plan with neither a product join nor a spool over the limit (nor one too large to print): such a plan runs with a note. Pure.

_empty

_empty(state: str, reason: str = '', **extra) -> dict

_open_connection

_open_connection()

(conn, None) or (None, reason): a raw teradatasql connection from TDFS4DS_TD_*.

measure

measure(old_select: str, new_select: str, *, entity_columns, feature_columns=None, conn=None, progress: Optional[Callable[[str], None]] = None, cancel_event: Optional[Event] = None, force: bool = False, max_seconds: Optional[float] = None, reference: Optional[dict] = None) -> dict

Compute both SELECTs in full into volatile tables, compare them and drop them. Never raises for a database error (returned whole in reason / notes); raises ValueError for bad arguments.

reference: the process's execution log (efficiency.reference of the study, :func:tdfs4ds.impact_reference.read_execution_reference); it raises the gate's limits to its logged median when higher, and the measured seconds are reported beside it (reference).

Returns {state, reason, old, new, identical_columns, differing, compared_columns, only_old, only_new, n_compared, notes, dropped, explain, limits, reference, session, tag}; state is done / refused / failed / cancelled. old / new: {rows, seconds, cpu_s, io, dbql, columns}. differing: {column: {n_differs, n_compared, null_changes, examples: [{key, old, new}]}}.

_v

_v(x)

_close

_close(cur) -> None

assign_dbql

assign_dbql(found, sides: Dict[str, dict]) -> None

Put the CPU seconds and I/O of each CREATE (DBQL rows (QueryText, AMPCPUTime, TotalIOCount), newest first) into sides ({old: {...}, new: {...}}). Pure.

_dbql

_dbql(rows, session, sides, tag=None) -> None

CPU seconds and I/O of each CREATE from DBQL, or None with the reason.

read_resources

read_resources(session=None, tag: Optional[str] = None, *, run_sql: Optional[Callable] = None, conn=None) -> dict

The CPU seconds and I/O of a finished measurement, read later from DBQL by its query band tag (or its session number). Read only (one SELECT on DBC.QryLogV). {state, reason, old, new}, state ok / pending (DBQL not written yet) / failed; never raises for a database error.

run_sql (sql -> rows) replaces the database; by default the measurement's own kind of connection is opened from TDFS4DS_TD_* (raw teradatasql, never teradataml's shared context).

_drop_all

_drop_all(conn, created, res) -> Optional[bool]

Remove the tables created (also after an error or a cancel), then prove they are gone (nothing created: nothing to prove).

measure_args_from_model

measure_args_from_model(model: dict, new_sql: str) -> dict

{old_select, new_select, entity_columns, feature_columns, reference} for the edited object of an impact model (reference = the study's efficiency.reference, or None). Raises ValueError when the study cannot be measured (no new SQL, no object, no key).